循环遍历多维数组以从子数组中获取特定结果

时间:2014-06-27 12:00:03

标签: php arrays multidimensional-array foreach

我有一个数组,我想从数组中提取一些数据。这对我来说通常没问题,但这次对我来说有点不同。

我有这个数组:

$arrParcelLabelNumber = array
(
    "parcelLabelNumber" => array
    (
        0 => "10",
        1 => "20"
    ),
    "weight" => array
    (
        0 => "1111",
        1 => "2222"
    )
);

我想得到以下结果: 10 = 1111, 20 = 2222

这意味着我想要parcelLabelNumber的值,其中键与重量相同,然后我也想要它们都相同的重量值。

我尝试了几种方法,但都没有用。

新代码:

$arrParcelLabelNumber = array
(
    "parcelLabelNumber" => array
    (
        0 => "09988014801055",
        1 => "09988014801056"
    ),
    "weight" => array
    (
        0 => "1111",
        1 => "2222"
    )
);

foreach($arrParcelLabelNumber as $val){
     foreach($val['parcelLabelNumber'] as $key=>$v){
        echo $val['weight'][$key] . "=" . $v;
      }
}

2 个答案:

答案 0 :(得分:1)

foreach($arrParcelLabelNumber as $val){
     foreach($val['parcelLabelNumber'] as $key=>$v){
         echo $val['weight'][$key] . "=" . $v;
      }

}

或者,如果您想将它们存储为关键值对进行检索......

 $newarray=array();
 foreach($arrParcelLabelNumber as $val){
     foreach($val['parcelLabelNumber'] as $key=>$v){
        $newarray[$val['weight'][$key]] = $v;
     }
 }
 var_dump($newarray);

或者作为数组中的一对......

 $newarray=array();
 foreach($arrParcelLabelNumber as $val){
    foreach($val['parcelLabelNumber'] as $key=>$v){
       $newarray[]=array('parcelLabelNumber'=>$v,'weight'=> $val['weight'][$key]);

    }
 }

答案 1 :(得分:1)

你也可以做一个简单的事情:

$c = count($arrParcelLabelNumber["parcelLabelNumber"]);

for ($i = 0; $i< $c; $i++)
{
    if(isset($arrParcelLabelNumber["parcelLabelNumber"][$i]) && isset($arrParcelLabelNumber["weight"][$i])){
        echo $arrParcelLabelNumber["parcelLabelNumber"][$i] . " = " . $arrParcelLabelNumber["weight"][$i];
    }
}