How to convert list of arrays with parallel properties to a list of object-like arrays in php

one text

Solution:

The following logic might help you on your way.

There are basically two ways to arrive at the desired outcome. The first assumes labels 'x' and 'y' can be hard coded, and used to reference the different 'points' in the source array $points. Result: array $newPoints0.

Alternatively, you could have these 'labels' change in your source array. To allow for this, we first get the keys, and work in much the same way to rearrange your source array. Result: array $newPoints1

<?php

$points = [
    'x' => [1, 3, 5],
    'y' => [2, 4, 6],
];

// use labels 'x' and 'y' (hard coded)
$size = count($points['x']);
for($i=0; $i < $size; $i++) {
    $newPoints0[$i] = ['x' => $points['x'][$i], 'y' => $points['y'][$i]];
}
echo '<pre>';
print_r($newPoints0);
echo '</pre>';

// labels 'x' and 'y' could change (dynamic)
$keys = array_keys($points);
$x = $points[$keys[0]]; // fetch label
$y = $points[$keys[1]]; // fetch label
$size = count($x);
for($i=0; $i < $size; $i++) {
    $newPoints1[$i] = [$keys[0] => $x[$i], $keys[1] => $y[$i]];
}

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

working demo

Output:

Array
(
    [0] => Array
        (
            [x] => 1
            [y] => 2
        )

    [1] => Array
        (
            [x] => 3
            [y] => 4
        )

    [2] => Array
        (
            [x] => 5
            [y] => 6
        )

)
Array
(
    [0] => Array
        (
            [x] => 1
            [y] => 2
        )

    [1] => Array
        (
            [x] => 3
            [y] => 4
        )

    [2] => Array
        (
            [x] => 5
            [y] => 6
        )

)

Source