-2

I have an array with

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"
  }
}

How to get an array with [["2","56"],["1","46"],["3","61"]] ?

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
benoît
  • 1,473
  • 3
  • 13
  • 31

4 Answers4

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);
Jonathon
  • 15,873
  • 11
  • 73
  • 92
  • OK for this, but I have 11 and more keys (not only foo_id and bar_id)… so there is no "magic" function to rotate my array. – benoît Aug 20 '14 at 13:22
  • You could easily get the array keys (Using: http://php.net/manual/en/function.array-keys.php) and if you can find out or already know the number of elements in each of the sub-arrays, you should be able to do it. – Jonathon Aug 20 '14 at 13:52
  • Yes I know, I will do my own function. – benoît Aug 20 '14 at 13:53
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]);
   }
Saswat
  • 12,320
  • 16
  • 77
  • 156
1
$food = $arr['food_id'];
$bar = $arr['bar_id'];
$result = array();

for ($i = 0; $i <count($food); $i++) {
    $result[] = array($bar[$i], $food[$i]);
}
Smruti Singh
  • 565
  • 1
  • 4
  • 14
0
$new_array = array();

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