如何删除包含特定索引的多维数组的元素?

时间:2016-02-26 16:15:48

标签: php

在我存储在$_SESSION['doc_brick_array']中的以下数组中,我试图找到brick0的元素。我想删除此元素,然后重新索引外部数组。我怎么能这样做?

Array
(
    [0] => Array
        (
            [brick0] => Array
                (
                    [city_name] => Lahore
                    [clinic_name] => shifa hospital
                    [attendant_name] => ali
                    [drd1_cell1] => 03017666454
                    [mbv] => 666
                    [brick_name] => LHR-0002
                    [clinic_address] => i-8 markaz
                    [drd1_phone] => 9798797
                    [drd1_cell2] => 04037777888
                    [drd1_email] => abc@yahoo.com
                    [visit_time] => m
                )

        )

    [1] => Array
        (
            [brick1] => Array
                (
                    [city_name] => Rawalpindi
                    [clinic_name] => aljanat hospital
                    [attendant_name] => kanzal
                    [drd1_cell1] => 03014544567
                    [mbv] => 6000
                    [brick_name] => 
                    [clinic_address] => i-9 markaz
                    [drd1_phone] => 07337837
                    [drd1_cell2] => 03017767575
                    [drd1_email] => abcd@yahoo.com
                    [visit_time] => m
                )

        )

)

我尝试过的代码

for($g=0; $g<=count($_SESSION['doc_brick_array']); $g++){
    if (($key = array_search($brick_code, $_SESSION['doc_brick_array'][$g])) !== false) {   
        unset($_SESSION['doc_brick_array'][$key]);  
        $_SESSION['doc_brick_array'] = array_values($_SESSION['doc_brick_array']);
    }   
}

2 个答案:

答案 0 :(得分:0)

我认为你在这里的是array_values(),来自PHP.net网站

  

array_values()返回数组中的所有值并对其进行索引   数字数组。

举个例子:

$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')

答案 1 :(得分:0)

您可以使用array_filter删除$_SESSION['doc_brick_array']中包含brick0密钥的所有元素。

$x = array_filter($_SESSION['doc_brick_array']), function($y) {
         return !isset($y['brick0']);
     });

然后使用array_values重新构建结果索引。

$_SESSION['doc_brick_array']) = array_values($x);