php数组中的非法Offset错误

时间:2014-06-13 00:10:41

标签: php arrays

我有一个看起来像这样的数组,我正在循环: 数组名称是$ test

Array
(
[ven1] => Array
    (
        [0] => Array
            (
                [0] => ven1-center1
                [1] => ven1
                [2] => Address
            )

        [1] => Array
            (
                [0] => ven1-center2
                [1] => ven1
                [2] => Address
            )

        [2] => Array
            (
                [0] => ven1-center3
                [1] => ven1
                [2] => Address
            )

           .
           .
           .


 [ven2] => Array
    (
        [20] => Array
            (
                [0] => ven2-center1
                [1] => ven2
                [2] => Address
            )

        [21] => Array
            (
                [0] => ven2-center2
                [1] => ven2
                [2] => Address
            )

        [22] => Array
            (
                [0] => ven2-center3
                [1] => ven2
                [2] => Address
            )

我有下面的PHP代码来循环整个数组,从最里面的维度获取[0]的所有值,将它们存储到名为$ k的数组中。 当我运行下面的代码时,我得到{c}的所有值的Notice: Undefined offset:

    for($c = 0; $c < 42; $c++){
        foreach($test as $k =>  $v){
          if($test[$k][$c][1] == $k){
           $k = $test[$k][$c][0];
         }
       }
     }

我正在寻找的输出是

$ven1 = array("ven1-center1","ven1-center2","ven1-center3","ven1-center4")
$ven2 = array("ven1-center1","ven1-center2","ven1-center3","ven1-center4")

1 个答案:

答案 0 :(得分:1)

我认为这会做你想要的......假设我正确地解释了你的问题:

foreach($test as $varname => $array){
   foreach($array as $row) {
       if ($row[1] == $varname) ${$varname}[] = $row[0];
   }
}

var_dump($ven1);
var_dump($ven2);