Print two arrays side by side

4

How to join two arrays with the index of array 1 following the index of array 2 .

Join data:

descricao

array1= datacol1, datacol2, datacol3, datacol4

array2= collinha1, collinha2, collinha3 ,collinha4 

Print like this:

  

description, datacol1, collinha1

     

description, datacol2, collinha2

     

description, datacol3, collinha3

     

description, datacol4, collinha4

<?php
$desc1 = 'Listar=';
$nome['24-01-2016'] = 'João';
$nome['25-01-2016'] = 'Telma';
$nome['26-01-2016'] = 'Joana';
$nome['27-01-2016'] = 'Thiago';
$nome['28-01-2016'] = 'Marcio';
$nome['29-01-2016'] = 'Juliana';
$nome['30-01-2016'] = 'Marcos';
$nome['31-01-2016'] = 'Mariana';

foreach($nome as $indice => $valor){

print $desc1;
print '=>>>';
print $indice;
print '-';
print $valor;
print'<br>';

}
?>
    
asked by anonymous 24.01.2016 / 22:45

2 answers

8

The simplest way to do this would be with for (this would not join the arrays , but as I realized you just want to print them together), it would look like this:

<?php

// your code goes here
$arr1 = array ('datacol1', 'datacol2', 'datacol3', 'datacol4');

$arr2= array ('collinha1', 'collinha2', 'collinha3', 'collinha4');

for($i = 0; $i < count($arr1); $i ++)
{
    echo 'descricao, '.$arr1[$i].', '.$arr2[$i].'<br>\n';
}

No Ideone

    
25.01.2016 / 01:39
4

I would do with a array_map to generate an array "side by side" and then iterate it with foreach .

$array1 = [1, 2, 3];

$array2 = [1, 2, 3, 4];

foreach (array_map(null, $array1, $array2) as $key => $value) {

    echo $value[0], ' e ', $value[1];

}

Using array_map with more than array and with null in the first parameter, instead of a callback, causes you to generate an array (based on the example given in that response) like this: / p>

[
   [1,1], [2, 2], [3,3], [null, 4]
]

Optionally, if you are using a version equal to or higher than PHP 5.5, you can use foreach together with list .

foreach(array_map(null, $array1, $array2) as $key => list($a, $b)) {

    echo $a, ' e ', $b;
}
    
25.01.2016 / 11:42