取消设置多维数组中的特定变量

时间:2014-09-23 18:16:34

标签: php arrays multidimensional-array

我无法弄清楚这是怎么回事。我的第一次尝试涉及使用引用并在引用上调用unset只是取消链接引用。我尝试了递归,但无法使其工作,然后我尝试了array_walk和array_filter但没有成功。这是一个简单的例子,演示了我想要做的事情。

<?
class Sample {
    //Please note this can have a completely variable amount of vars/dimensions
    $data = array("system" => array("value1","value2"), "session" => array("value1"));

    public function erase($value){
         //Here I am suppose to somehow delete that exists in $this->data
    }
    public function display(){
         print_r($this->data);
    }
 }


 $Sample = new Sample();
 $Sample->erase(array("system","value1"));
 //I am extremely flexible on the format of the erase parameter ($value)
 $Sample->display();

 should output with the variable unset($this->data["system"]["value1"]) :

 array("system" => array("value2"), "session" => array("value1")

Ohgodwhy帮助创建了eval.in with a slighly modified example

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

如果您始终传入包含值的数组的键名,后跟值,我们可以使用array_search来执行此操作。

if(false !== $key = array_search($value[1], $this->data[$value[0]])):
    unset($this->data[$value[0]][$key]);
endif;

这是你的eval.in example

答案 1 :(得分:1)

我已经完成了这项功能并且工作得很好

function erase(array &$arr, array $children)
{
    $ref = &$arr;
    foreach ($children as $child)
        if (is_array($ref) && array_key_exists($child, $ref)) {
            $toUnset = &$ref;
            $ref = &$ref[$child];
        } else
            throw new Exception('Path does\'nt exist');
    unset($toUnset[end($children)]);
}

示例1

以下是您如何取消设置$arr['session']['session3']['nestedSession2']

的示例
$arr = [
    "system" => [
        "system1" => "value1",
        "system2" => "value2"
    ],
    "session" => [
        "session1" => "value3",
        "session2" => "value4",
        "session3" => [
            "nestedSession1" => "value5",
            "nestedSession2" => "value6",
        ],
    ],
];

print_r($arr);
erase($arr, array('session', 'session3', 'nestedSession2'));
print_r($arr);

示例2

它甚至可以取消设置整个嵌套数组,以下是你将如何处理它(处理错误):

print_r($arr);
try {
    erase($arr, array('session', 'session3'));
}  catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
print_r($arr);

示例3

它也适用于非相关数组:

$arr = array('fruit1', 'fruit2', 'fruit3');
print_r($arr);
try {
    erase($arr, array(0));
}  catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
print_r($arr);

示例4

如果出现错误:

$arr = array('fruit1', 'fruit2', 'fruit3');
print_r($arr);
try {
    erase($arr, array('pathThatDoesNotExit'));
}  catch (Exception $e) {
    // do what you got to do here in case of error (if the path you gave doesn't exist)!
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
print_r($arr);