How can I rearrange this array?

Asked

Viewed 63 times

-2

I have the following array:

$array_atual = array (

    'id_item' => array('1', '3'), // 'id_item', 'id_item'
    'cantidad' => array('15', '10') // 'cantidad', 'cantidad'
);

I’d like to leave it this way:

$array_final (

    '0' => array('1', '15'); // 'id_item', 'cantidad'
    '1' => array('3', '10')     // 'id_item', 'cantidad'
);

How can I make that change?

  • This is basically a "matrix transposition," which I’ve already answered here

1 answer

1

Always allow the keys to match the array id_item and cantidad, you can do it in the following way:

$array_final = array();
$array_atual = array (

    'id_item' => array('1', '3'), // 'id_item', 'id_item'
    'cantidad' => array('15', '10') // 'cantidad', 'cantidad'
);

foreach($array_atual['id_item'] as $key => $value){
     $newArray = array($value, $array_atual['cantidad'][$key]);
     array_push($array_final, $newArray);
}

Example in Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.