I am currently trying to convert this 2D array into a sentence, this is the result I'm expecting :
From :
Array
(
[NUM] => Array
( [0] => 101
[1] => 102
[2] => 103
...
)
[NOM] => Array
( [0] => LEPETIT
[1] => DURAND
[2] => DUPONT
...
)
[PRENOM] => Array
( [0] => Lukos
[1] => Pierre
[2] => Thiery
...
)
[...]
)
Printed text I want :
NUM:101 NOM:LEPETIT PRENOM:Lukos ...
NUM:102 NOM:DURAND PRENOM:Pierre ...
...
I tried using multiple foreach but I can't manage to use one 'echo' using the values.
CodePudding user response:
This code makes a couple of assumptions.
- Your data is in a "list", see this for a definition and a polyfil for older version
- Every child array has the exact same number of items
- Your outer keys are not always the same so we need to scan and collet them first
The first for
loop exists to mostly sanity check the above. If those assumptions are actual facts this can be simplified further. Once we do that, the second one just loops over the known keys and then loops from 0
to the end of the list build arrays of strings.
$data = [
'NUM' => [
101,
102,
103,
],
'NOM' => [
'Smith',
'Robson',
'Daniels',
],
'PRENOM' => [
'Alice',
'Bob',
'Charlie',
],
];
// Grab all possible outer keys
$outerKeys = array_keys($data);
// Make sure all child arrays are the same size
$innerCount = null;
foreach($outerKeys as $key) {
// Also make sure that we've got a list so that we don't have to keep
// track of child keys. For a 7.x polyfill see
// https://www.php.net/manual/en/function.array-is-list.php
if(!array_is_list($data[$key])){
throw new RuntimeException('Child array is not a list');
}
// Count the first item
if(null === $innerCount){
$innerCount = count($data[$key]);
break;
}
// Compare the known count with the current child array
if($innerCount !== count($data[$key])){
throw new RuntimeException('Child array does not have equal item count');
}
}
$lines = [];
for($idx = 0; $idx < $innerCount; $idx ){
$buf = [];
foreach($outerKeys as $key){
$buf[] = $key . ':' . $data[$key][$idx];
}
$lines[] = implode(' ', $buf);
}
echo implode(PHP_EOL, $lines);
Demo here: https://3v4l.org/fU4vX
CodePudding user response:
You can concat a string using .
// $yourArray = ...
$maxIndex = min(count($yourArray['NUM']), count($yourArray['NOM']), count($yourArray['PRENOM']));
for($i = 0; $i < $maxIndex; $i ) {
echo('NUM:' . $yourArray['NUM'][$i] . ' NOM:' . $yourArray['NOM'][$i] . ' PRENOM:' . $yourArray['PRENOM'][$I]) . "\n";
}