1

I have multidimensional array which looks like this. This is my snippet down below:

$tyreSpec = array(
    'width_id' => array(
        0 => '8',
        1 => '24'
    ),
    'profile_id' => array(
        0 => '8',
        1 => '13'
    ),
    'diameter_id' => array(
        0 => '4',
        1 => '13'
    ),
    'speed_id' => array(
        0 => '6',
        1 => '13'
    ),
    'load_id' => array(
        0 => '12',
        1 => '31'
    )
);

How can I create an array like this from the above one?

$toDb = array (
    array(
          'width_id' => 8,
          'profile_id' => 8,
          'diameter_id' => 4,           
          'speed_id' => 6,
          'load_id' => 12
    ),
    array(
          'width_id' => 24,
          'profile_id' => 13,
          'diameter_id' => 13,           
          'speed_id' => 13,
          'load_id' => 31
    )
);

This is my code down below I can't get it done:

$ToDb = array();
//$i = 0;
$count = 0;
foreach($tyreSpec as $row ) {
    $count = count($row);
}

for($i = 0; $i < $count; $i++) {
    foreach($tyreSpec as $row) {
        array_push($ToDb, $row[$i]);
    }
}
fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
Share Knowledge
  • 297
  • 3
  • 18

3 Answers3

4

You can use two simple loops to achieve your goal:

$toDb = array();
foreach ($tyreSpec as $key=>$val) {
    for ($i=0; $i<count($val); ++$i)
        $toDb[$i][$key] = $val[$i];
}
fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
0

I think you are looking for this:

// $source is your input array
$result = [];$result = [];
array_walk($source, function($v,$k) use (&$result){
    $result[0][$k] = $v[0];
    $result[1][$k] = $v[1];
});

print_r($result);

Demo is Here

Ali
  • 1,408
  • 10
  • 17
0
    $initArray = 
    array (
      'width_id' => 
        array (
          0 => string '8',
          1 => string '24'
        ),
      'profile_id' => 
        array (
          0 => string '8',
          1 => string '13'
        ),
      'diameter_id' => 
        array (
          0 => string '4',
          1 => string '13'
        ), 
      'speed_id' => 
        array (
          0 => string '6',
          1 => string '13' 
       ),
      'load_id' => 
        array (
          0 => string '12', 
          1 => string '31'
        )
    )

$newArray = Array();

foreach ($innitArray as $key => $value){
   $newArray[$key][0] = $innitArray[$key][$vallue][0];
   $newArray[$key][1] = $innitArray[$key][$vallue][1];
}
dios231
  • 714
  • 1
  • 9
  • 21