C
C
CreativeStory2020-05-07 06:18:30
PHP
CreativeStory, 2020-05-07 06:18:30

How to concatenate elements in an array correctly?

There is an array

$arr = [
    'color' => [ 'red', 'blue' ],
    'size' => [ 23, 55 ],
    'price' => [ 100, 200 ]
]


How can I collect a new array by values ​​so that the result is as follows
[
    [ 'red', 23, 100 ],
    [ 'blue', 55, 200 ]
]


I do through one place, as it seems to me. So
$newArr = [];
for ($i = 0; $i < count($arr['color']; $i++) {
    array_push($newArr, [ $arr['color'][$i], $arr['size'][$i], $arr['price'][$i] ] );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Shvedov, 2020-05-07
@CreativeStory

https://www.php.net/manual/en/function.array-map.php

<?php
$a = [1, 2, 3, 4, 5];
$b = ['one', 'two', 'three', 'four', 'five'];
$c = ['uno', 'dos', 'tres', 'cuatro', 'cinco'];

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question