2

Here I have two multidimensional arrays. I have to combine them to make one multidimensional array. I tried but it is not happening. I don't know what I am doing wrong. I want to make productId as index, then values.

With this code:

$array1 = Array (
    "3" => Array ( "productId" => 3, "brandName" => "Honor" ),
    "4" => Array ( "productId" => 4, "brandName" => "Puma" )
);
$array2 = Array ( "5" => Array ( "productId" => 5, "brandName" => "Dell" ) ) 
$result = array_merge($array1,$array2);
print_r($result );

I get:

Array (
    "0" => Array ( "productId" => 3, "brandName" => "Honor" ),
    "1" => Array ( "productId" => 4, "brandName" => "Puma" ),
    "2" => Array ( "productId" => 5, "brandName" => "Puma" )
)

The above result is not my expected answer because index is automatically assigning. In my case, the index is productId.

Expected Result:

Array (
    "3" => Array ( "productId" => 3, "brandName" => "Honor" ),
    "4" => Array ( "productId" => 4, "brandName" => "Puma" ),
    "5" => Array ( "productId" => 5, "brandName" => "Dell" )
)
0

2 Answers 2

1

array_column is perfect for this situation. Just pass null for column key and "productId" for index key.

$result = array_merge($array1, $array2);
$final = array_column($result, null, "productId");
Sign up to request clarification or add additional context in comments.

Comments

0

This is expected with array_merge

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

As you may have discovered, "numeric" also includes numeric strings.

It looks like your product IDs are already used as the array keys, so you should be able to get the result you want by using the + (union) operator instead.

$result = $array1 + $array2;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.