如何将多维数组键更改为Childs键值?

I'm trying to rename the parent keys in a Multidimensional Array to the value of a child key.

For example in the code below I would like to change the key [0] to [111] and the key [1] to [222] so it is easy for me to identify keys later for an array merge.

Array (
[0] => Array ( [product_id] => 111 [product_name] => Foo [quantity] => 4 )
[1] => Array ( [product_id] => 222 [product_name] => Bar [quantity] => 2 )
)

I've tried various ways of doing this but after entering a loop, I can't work out how to affect the parent key and assume it's impossible after passing it to a variable. Is there an easy solution to change the key I am missing or is it a case of entering the loop and rebuilding a new array with the desired key?

One-line solution using array_combine and array_column functions:

$result = array_combine(array_column($arr, 'product_id'), $arr);
print_r($result);

The output:

Array
(
    [111] => Array
        (
            [product_id] => 111
            [product_name] => Foo
            [quantity] => 4
        )

    [222] => Array
        (
            [product_id] => 222
            [product_name] => Bar
            [quantity] => 2
        )
)

You need to create a new array, such as:

$original = array(
[0] => Array ( [product_id] => 111 [product_name] => Foo [quantity] => 4 )
[1] => Array ( [product_id] => 222 [product_name] => Bar [quantity] => 2 )
)

$new = array();
foreach ($original as $val) {
    $new[$val->product_id] = $val;
}

create new array use foreach to loop through your old array and assign the value of new one

 <?php
    $oldArray[0] = Array ("product_id"=> 111 , "product_name" => "Foo" , "quantity" => 4 );
    $oldArray[1] = Array ("product_id"=> 222 , "product_name" => "Bar" , "quantity" => 2 );
    $newArray=array();
    foreach($oldArray as $childarray){
    $newArray[$childarray['product_id']]=array('product_id'=>$childarray["product_id"],'product_name'=>$childarray["product_name"],'quantity'=>$childarray["quantity"]);
    }
    echo "<pre>";
    print_r($newArray);
    echo "</pre>";
    ?>