php - Explode and transpose nominated comma-separated strings of an associative array

723

I have an array with comma-separated values like below:

array:5 [
  "manufacturer" => "BB"
  "width" => "245,225, ..."
  "height" => "45,65, ..."
  "diameter" => "19,17, ..."
  "type" => "AA"
]

There is no limit to how many comma-separated values there may be, but all 3 of them will have same length.

From this, I want to get transposed output like below:

[
    245,
    45,
    19,
],
[
    45,
    65,
    17
]

So far, I have tried following code.

$mandatoryFields = [
    'width',
    'height',
    'diameter',
];

$finalArray = [];
for ($i = 0; $i < 2; $i+=1) {
    foreach ($mandatoryFields as $mandatoryField) {
        $fieldArray = explode(',', $executionArray[$mandatoryField]);
        $finalArray[] = [
            $fieldArray[$i]
        ];
    }
}
dd($finalArray);

But it is returning me:

array:6 [
  0 => array:1 [
    0 => "245"
  ]
  1 => array:1 [
    0 => "45"
  ]
  2 => array:1 [
    0 => "19"
  ]
  3 => array:1 [
    0 => "225"
  ]
  4 => array:1 [
    0 => "65"
  ]
  5 => array:1 [
    0 => "17"
  ]
]
428

Answer

Solution:

The following logic might help you solve your issue:

<?php
$arr = [
   "manufacturer" => "BB",
   "width" => "245, 225",
   "height" => "45, 65",
   "diameter" => "19, 17",
   "type" => "AA",
];

foreach ($arr as $key => $val) {
    $split[$key] = explode(',', $val);
}

$mandatoryFields = [
    'width',
    'height',
    'diameter',
];
// keep only mandatory fields
$split = array_intersect_key($split, array_flip($mandatoryFields));

$items = count($split[$mandatoryFields[0]]); // number of 'items' per mandatory field
for ($i = 0; $i < $items; $i++) {
    $result[$i] = array_column($split, $i);
}

echo '<pre>';
print_r($result);
echo '</pre>';

Output:

Array
(
    [0] => Array
        (
            [0] => 245
            [1] => 45
            [2] => 19
        )

    [1] => Array
        (
            [0] =>  225
            [1] =>  65
            [2] =>  17
        )

)
642

Answer

Solution:

Essentially, this is an "explode & transpose" task. If the required columns are known, then they can be hardcoded like this: (Demo)

var_export(
    array_map(
        null,
        explode(', ', $arr['width']),
        explode(', ', $arr['height']),
        explode(', ', $arr['diameter'])
    )
);

Output:

array (
  0 => 
  array (
    0 => '245',
    1 => '45',
    2 => '19',
  ),
  1 => 
  array (
    0 => '225',
    1 => '65',
    2 => '17',
  ),
)

If the columns need to be dynamic, then map the required fields, explode on commas and unpack the generated rows to maintain a functional coding style: (Demo)

var_export(
    array_map(
        null,
        ...array_map(
            fn($f) => explode(', ', $arr[$f]),
            $mandatoryFields
        )
    )
);

People are also looking for solutions to the problem: php - foreach() Invalid argument

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.