Home > Back-end >  How to add value of array 1 to key of array 2 in 1 for loop using PHP?
How to add value of array 1 to key of array 2 in 1 for loop using PHP?

Time:06-17

I also just learned about PHP programming, you guys in the forum can handle the following problem for me. There are 3 data arrays as follows, in these 3 arrays have different array lengths. I'm trying to merge into a new array. But it doesn't work as intended

Here is my code

    $array1 = [
    [
        "title" => "Title array1 1",
        "type" => "array1"
    ],
    [
        "title" => "Title array1 2",
        "type" => "array1",
    ],
    [
        "title" => "Title array1 3",
        "type" => "array1"
    ]
];

$array2 = [
    [
        "title" => "Title array2 1",
        "type" => "array2",
    ],
    [
        "title" => "Title array2 2",
        "type" => "array2"
    ]
];

$array3 = [
    [
        "title" => "Title array3 1",
        "type" => "array3"
    ]
];

$newArray = [];
for ($i = 0; $i < count($array1); $i  ) {
    @array_push($newArray, [
        'array1' => $array1[$i]['title'],
        'array2' => $array2[$i]['title'],
        'array3' => $array3[$i]['title']
    ]);
}

echo "<pre>";
print_r($newArray);
/** Output ==>
Array
(
    [0] => Array
        (
            [array1] => Title array1 1
            [array2] => Title array2 1
            [array3] => Title array3 1
        )

    [1] => Array
        (
            [array1] => Title array1 2
            [array2] => Title array2 2
            [array3] => 
        )

    [2] => Array
        (
            [array1] => Title array1 3
            [array2] => 
            [array3] => 
        )
)
*/

Help me create a new array like this

 Array
   (
    [0] => Array
    (
        [array1] => Title array1 1
        [array2] => Title array2 1
        [array3] => Title array3 1
    )

[1] => Array
    (
        [array1] => Title array1 2
        [array2] => Title array2 2
        [array3] => Title array3 1 // Add here
    )

[2] => Array
    (
        [array1] => Title array1 3
        [array2] => Title array2 1 // Add here
        [array3] => Title array3 1 // Add here
    )
)

I sincerely thank

CodePudding user response:

You're almost there. You can use the % operator to get the correct index from the input arrays so that you can rotate through their values for each new array.

$newArray = [];

for ($i = 0; $i < count($array1); $i  ) {
    $newArray[] = [
        'array1' => $array1[$i]['title'],
        'array2' => $array2[$i % count($array2)]['title'],
        'array3' => $array3[$i % count($array3)]['title']
    ];
}

For larger arrays you should count the other arrays before the loop and save the values in variables to avoid recounting them repeatedly. For this little example it won't make much difference.

A couple of side notes:

  • avoid using the error suppression operator (@). Errors contain useful information that you shouldn't hide from yourself.
  • you don't need array_push() to add one item to an array. You can just use [] like I've shown above.

CodePudding user response:

You can map the three arrays to form a consolidated multi-dimensional array. Assuming the first array will always have at least one row containing a title value, you can fallback to that value if a particular column is missing/undeclared.

There is no need to count() arrays on each iteration or perform a modulus calculation; null coalescing will work nicely.

Code: (Demo)

var_export(
    array_map(
        fn(...$rows) => [
            'array1' => $rows[0]['title'] ?? $array1[0]['title'],
            'array2' => $rows[1]['title'] ?? $array1[0]['title'],
            'array3' => $rows[2]['title'] ?? $array1[0]['title'],
        ],
        $array1,
        $array2,
        $array3
    )
);

or without the variadic / spread operator: (Demo)

var_export(
    array_map(
        fn($row1, $row2, $row3) => [
            'array1' => $row1['title'] ?? $array1[0]['title'],
            'array2' => $row2['title'] ?? $array1[0]['title'],
            'array3' => $row3['title'] ?? $array1[0]['title'],
        ],
        $array1,
        $array2,
        $array3
    )
);
  • Related