gpt4 book ai didi

Php 算法 - 如何在没有 eval 的情况下实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:04:12 24 4
gpt4 key购买 nike

我有一个类通过使用 words.separated.by.dots 键来保存数据存储/访问数据,它的行为如下所示:

    $object = new MyArray()
$object->setParam('user.name','marcelo');
$object->setParam('user.email','some@email.com');

$object->getParams();

/*
array(
'user' => array(
'name' => 'marcelo',
'email' => 'some@email.com'
)
);
*/

它正在工作,但是方法 unsetParam() 被可怕地实现了。发生这种情况是因为我不知道如何在没有 eval() 函数的情况下实现这一目标。虽然它有效,但我发现它是一个非常具有挑战性的算法,您可能会发现在没有 eval() 的情况下尝试实现它会很有趣。

class MyArray {
/**
* @param string $key
* @return Mura_Session_Abstract
*/
public function unsetParam($key)
{
$params = $this->getParams();
$tmp = $params;
$keys = explode('.', $key);

foreach ($keys as $key) {
if (!isset($tmp[$key])) {
return $this;
}
$tmp = $tmp[$key];
}

// bad code!
$eval = "unset(\$params['" . implode("']['", $keys) . "']);";
eval($eval);

$this->setParams($params);
return $this;
}
}

测试方法:

public function testCanUnsetNestedParam()
{
$params = array(
'1' => array(
'1' => array(
'1' => array(
'1' => 'one',
'2' => 'two',
'3' => 'three',
),
'2' => array(
'1' => 'one',
'2' => 'two',
'3' => 'three',
),
)
),
'2' => 'something'
);

$session = $this->newSession();
$session->setParams($params);

unset($params['1']['1']['1']);
$session->unsetParam('1.1.1');

$this->assertEquals($params, $session->getParams());
$this->assertEquals($params['1']['1']['2'], $session->getParam('1.1.2'));
}

最佳答案

是这个吗?

<?php
$params = array(
'1' => array(
'1' => array(
'1' => array(
'1' => 'one',
'2' => 'two',
'3' => 'three',
),
'2' => array(
'1' => 'one',
'2' => 'two',
'3' => 'three',
),
)
),
'2' => 'something'
);

function unsetParam( &$array, $paramString ) {
$cur =& $array;
$splitted = explode( ".", $paramString );
$len = count( $splitted ) - 1;

for( $i = 0; $i < $len; ++$i ) {

if( isset( $cur[ $splitted[ $i ] ] ) ) {
$cur =& $cur[ $splitted[ $i ] ];
}
else {
return false;
}


}

unset( $cur[ $splitted[$i] ] );


}

unsetParam( $params, "1.1.1");

print_r( $params );

/*
Array
(
[1] => Array
(
[1] => Array
(
[2] => Array
(
[1] => one
[2] => two
[3] => three
)

)

)

[2] => something
)
*/

关于Php 算法 - 如何在没有 eval 的情况下实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com