Join several arrays into one two-dimensional in PHP

0

I would like to join several arrays into a single two-dimensional array.

Each array corresponds to the data of a column and I would like to know if it is possible to put all together.

My arrays are in this format:

<?php
$Id =array("1","2","3");
$Auto =array("BMW","NISSAN","FORD");
$Precio =array("1000","2000","3000");

The objective that I would like to know if it is possible is to put the three arrays together in one, so that later I can go through them with a $listaAutos[i][j] loop.

Working with PHP 7.

    
asked by Carlos Daniel Zárate Ramírez 22.06.2018 в 05:47
source

1 answer

2
<?php

    $Id =array("1","2","3");
    $Auto =array("BMW","NISSAN","FORD");
    $Precio =array("1000","2000","3000");



for ($i=0;$i<count($Id);$i++){
    $listaAutos[$Id[$i]][]=$Auto[$i];
    $listaAutos[$Id[$i]][]=$Precio[$i];
}

    print_r($listaAutos);

This will result in an array like this:

Array
(
    [1] => Array
        (
            [0] => BMW
            [1] => 1000
        )

    [2] => Array
        (
            [0] => NISSAN
            [1] => 2000
        )

    [3] => Array
        (
            [0] => FORD
            [1] => 3000
        )

)

That you can access using numeric indexes $listaAutos[i][j]; as follows:

 for ($i=0;$i<count($listaAutos);$i++){
        for($j=0;$j<count($listaAutos[$i]);$j++){
            echo $listaAutos[$i][$j]."<br>";
        }
    }
    
answered by 22.06.2018 / 10:35
source