1

I've been stuck on this issue for a while now. I have a multidimensional array that I'd like to output in a certain way. Here is the array:

    array:3 [
      "First Name" => array:3 [
        0 => "BILLY"
        1 => "SALLY"
        2 => "TYLER"
      ]
      "Last Name" => array:3 [
        0 => "RAY"
        1 => "SUE"
        2 => "TERRIER"
      ]
      "HOBBY" => array:3 [
        0 => "PIANO"
        1 => "SKATING"
        2 => "BASKETBALL"
      ]
    ]

I'd like to have the final output be the following:

    BILLY|RAY|PIANO|
    SALLY|SUE|SKATING|
    TYLER|TERRIER|BASKETBALL|

Unfortunately with the existing code I have:


    $output = '';
     foreach($tempArray as $key => $value){
         $output .= $value[array_search($key,$tempArray)].$delimiter;  
     }

it only outputs the first index of each array like so:

    BILLY|RAY|PIANO|

So my question is how do I end up with the remaining two values? Should I create some sort or array and counter and and store each output this way: $newArray[$counter] = $output?

0

2 Answers 2

2

The array_column() function will fetch a column from a 2-dimensional array. Then just jam them all together.

$array = [
    "First Name" => ["BILLY", "SALLY", "TYLER"],
    "Last Name" => ["RAY", "SUE", "TERRIER"],
    "HOBBY" => ["PIANO", "SKATING", "BASKETBALL"],
];

$result = implode("|", array_column($array, 0)) . "\n";
$result .= implode("|", array_column($array, 1)) . "\n";
$result .= implode("|", array_column($array, 2));
echo $result;

As pointed out in a comment, you may not always know the length of the child arrays. That would mean wrapping this in a loop:

$iterations = count(reset($array));
$result = "";
for ($i = 0; $i <= $iterations; $i++) {
    $result .= implode("|", array_column($array, $i)) . "\n";
}
Sign up to request clarification or add additional context in comments.

Comments

0

If all three sub-arrays are always the same size, you could just use a for loop:

$array = [
    "First Name" => ["BILLY", "SALLY", "TYLER"],
    "Last Name" => ["RAY", "SUE", "TERRIER"],
    "HOBBY" => ["PIANO", "SKATING", "BASKETBALL"],
];

$result = '';
$size = count($array["First Name"]);
for($i = 0; $i < $size; $i++){
   $result.= "{$array['First Name'][$i]}|{$array['Last Name'][$i]}|{$array['HOBBY'][$i]}\r\n";
}
echo $result;

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.