Roberto Di Marco Roberto Di Marco - 4 months ago 10
PHP Question

Sorting an array in php

I get the data from a checkout form, when user have two or more product, I have this array.

Array(
[nome] => Array
(
[0] => Nature herbs
[1] => Nature Baby
)

[qty] => Array
(
[0] => 1
[1] => 2
)

[prezzo] => Array
(
[0] => $23.00
[1] => $34.00
)
)


But, how can I change it into something like this.

Array(
[0] => Array
(
[nome] => Nature herbs
[qty] => 1
[prezzo] => $23.00
)

[1] => Array
(
[nome] => Nature Baby
[qty] => 2
[prezzo] => $34.00

)
)


Thanks!

Answer

You could simply loop through the "nome" array and write all the data into a second array, using the same index.

$array2 = array();

for ($i = 0; $i < count($array1['nome']); $i++) {
    $array2[$i]['nome'] = $array1['nome'][$i];
    $array2[$i]['qty'] = $array1['qty'][$i];
    $array2[$i]['prezzo'] = $array1['prezzo'][$i];
}