John Davidson

php - Create multidimensional array from two arrays and set unique id as key of main array

0 comments
Message:


Think, I have two arrays as showing below:


$a1 = [1=>444,2=>555,3=>666,4=>777];
$a2 = [1=>888,2=>999,3=>444,4=>'',5=>123,6=>215];

Then, my new array should be :


Array
(
[1] => Array
(
['p1'] => 444
['p2'] => 888
),
[2] => Array
(
['p1'] => 555
['p2'] => 999
),
[3] => Array
(
['p1'] => 666
['p2'] => 444
),
[4] => Array
(
['p1'] => 777
['p2'] =>
)
)

I tried its as shown the code below. Its working for me, But my I know is there any other appropriate way to do this without looping in php?


foreach ($a1 as $k => $v) {
$nary[$k] = ['p1' => $v, 'p2'=>$a2[$k]];
}


My Answer:
Yes, you can achieve this without looping by using the array_map function in PHP. Here is an example code snippet:

php
$a1 = [1=>444,2=>555,3=>666,4=>777];
$a2 = [1=>888,2=>999,3=>444,4=>'',5=>123,6=>215];

$nary = array_map(function($p1, $p2) {
return ['p1' => $p1, 'p2' => $p2];
}, $a1, $a2);

print_r($nary);


This code snippet will produce the same output as your original code, but it uses the array_map function to create the multidimensional array without explicitly looping through the arrays.

Rate this post

4 of 5 based on 8746 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us