foreach with key和array

时间:2014-08-20 12:58:17

标签: php arrays array-key

我有一个

的数组
array(2) {
  ["bar_id"]=>
  array(3) {
    [0]=>
    string(1) "2"
    [1]=>
    string(1) "1"
    [2]=>
    string(1) "3"
  }
  ["foo_id"]=>
  array(3) {
    [0]=>
    string(2) "56"
    [1]=>
    string(2) "46"
    [2]=>
    string(2) "61"
  }
}

如何使用[["2","56"],["1","46"],["3","61"]]获取数组?

4 个答案:

答案 0 :(得分:3)

$foo = $arr['foo_id'];
$bar = $arr['bar_id'];
$result = array();
$count = count($foo);
for ($i = 0; $i < $count; $i++) {
    $result[] = array($bar[$i], $foo[$i]);
}
print_r($result);

答案 1 :(得分:1)

$parent_array = array(
                       'bar_id' => array('2','1','3'),
                        'food_id' => array('56','46','61')
                      );


$bar_array = $parent_array['bar_id'];
$food_array = $parent_array['food_id'];

$new_array = array();


for($i= 0 ; $i<count($bar_array); $i++)
   {
         $new_array[$i] = array($bar_array[$i],$food_array[$i]);
   }

答案 2 :(得分:1)

$food = $arr['food_id'];
$bar = $arr['bar_id'];
$result = array();

for ($i = 0; $i <count($food); $i++) {
    $result[] = array($bar[$i], $food[$i]);
}

答案 3 :(得分:0)

$new_array = array();

for ($i = 0; $i < count($array[0]); $i++){
    $new_array[] = new array(
        $array['bar_id'][$i],
        $array['foo_id'][$i],
    );
}