如何从php中的引用数组中删除元素?

时间:2014-04-23 06:56:40

标签: php arrays multidimensional-array

我在代码之前使用以获取每个第一个id并删除该id,但它显示错误undefine offset。

我不明白我在下面的代码中遗漏了什么?

$products = Array
    (
        [32] => Array
            (
                [0] => 44
                [1] => 45
                [2] => 926
                [3] => 927
                [4] => 930
                [5] => 931
            )

        [41] => Array
            (
                [0] => 928
                [1] => 933
                [2] => 969
                [3] => 970
                [4] => 971
                [5] => 972
                [6] => 973
                [7] => 974
                [8] => 975
                [9] => 976
                [10] => 977
                [11] => 978
                [12] => 979
                [13] => 980
                [14] => 981));

    $in_array = array();

    for($i=0;$i<12;)
    {
        foreach($products as &$brands):                 
            if(isset($brands[0]))
            {
                $id = $brands[0];// get the first element
                unset( $brands[0]); // have remove that element form products
                // But here it show error undefine offset 0

                array_push($in_array,$id);

                /*if(($key1 = array_search($id, $brands)) !== false) {
                     unset($brands[$key1]);
                }*/
                //I tried this too same error

                $i++;
            }           
        endforeach;     

    }

2 个答案:

答案 0 :(得分:0)

$brands[0]似乎不存在(我的代码中只看到32和41)。

如果你想删除$ products [32]中的第一个元素而不是你需要另一个foreach:

foreach($products as $brands) {
    foreach($brands as $brand) {
        //Here is where you can reach $brand[0](Which is 44 in $products[32])
    }
}

如果您要删除数组的第一个元素,可以使用array_shift

答案 1 :(得分:0)

在@CaptainCarl先生的帮助下,我改变了我的循环,它正常工作

  for($i=0;$i<12;)
            {
                foreach($products_ids as $key=>$brands):
                    if(isset($brands[0]))
                    {
                        $id = $brands[0];
                        array_push($in_array,$id);
                        array_shift($brands);
                        $i++;   
                    }
                    $products_ids[$key] = $brands;              
                endforeach;         
            }