简体   繁体   中英

Print php 2D array into a sentence

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.

This code makes a couple of assumptions.

  1. Your data is in a "list", see this for a definition and a polyfil for older version
  2. Every child array has the exact same number of items
  3. 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

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";
}

This is the simple task of transposing a matrix of data (Stack Overflow has a hundred demonstrations of this task -- I know because I linked most of them together).

Write a nested set of loops and write conditions to format your desired output strings.

Code: ( Demo )

$result = [];
foreach ($data as $k => $row) {
    foreach ($row as $i => $v) {
        if (!isset($result[$i])) {
            $result[$i] = '';
        } else {
            $result[$i] .= ' ';
        }
        $result[$i] .= "$k:$v";
    }
}
echo implode(PHP_EOL, $result);

Output:

NUM:101 NOM:Smith PRENOM:Alice
NUM:102 NOM:Robson PRENOM:Bob
NUM:103 NOM:Daniels PRENOM:Charlie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM