简体   繁体   中英

PHP rename key in Associative array

I've been searching through the articles on SO for this question and tried many of the solutions in my own code but it's not seeming to work.

I have the following array

$array[] = array("Order_no"=>$order_id,
                "Customer"=>$customer_id,
                "Product"=>$code_po,
                "Product_description"=>$code_description,
                "Position"=>$pos,
                "Qty"=>$item_qty
                );

I am looking to replace the "Order_no" key with a variable from a database query, lets assume in this case the variable is "new_name"

$new = "new_name";
$array[$new]=$array["Order_no"];
unset($array["Order_no"]);
print_r($array);

in the print_r statement I am getting the new_name coming through as the correct order number, but I am still seeing "Order_no" there also, which I shouldn't be seeing anymore.

Thanks.

This is your array:

Array
(
    [0] => Array
        (
            [Customer] => 2
            [Product] => 99
            [Order_no] => 12345
        )

)

One way to do it:

<?php

$arr[] = [
    "Order_no" => 12345,
    "Customer" => 00002,
    "Product"=> 99
];

$i_arr = $arr[0];

$i_arr["new_name"] = $i_arr["Order_no"];
unset($i_arr["Order_no"]);

$arr[0] = $i_arr;

print_r($arr);

Another way:

<?php

$arr[] = [
    "Order_no" => 12345,
    "Customer" => 00002,
    "Product"=> 99
];

$arr[0]["new_name"] = $arr[0]["Order_no"];
unset($arr[0]["Order_no"]);

print_r($arr);

To flatten your array out at any time:

<?php

$arr = $arr[0];
print_r($arr);

You are using extra level of array (by doing $array[] = ... ).

You should do it with [0] as first index as:

$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);

Live example: 3v4l

Another option is get ride of this extra level and init the array as:

$array = array("Order_no"=>$order_id, ...

As $array is also an array, you have to use index:

    $array[0][$new]=$array[0]["Order_no"];
    unset($array[0]["Order_no"]);

The other answers will work for the first time you add to the array, but they will always work on the first item in the array. Once you add another it will not work, so get the current key:

$array[key($array)][$new] = $array[key($array)]["Order_no"];
unset($array[key($array)]["Order_no"]);

If you want the first one, then call reset($array); first.

Change your variable to

$array=array("Order_no"=>$order_id,"Customer"=>$customer_id,"Product"=>$code_po,"Product_description"=>$code_description,"Position"=>$pos,"Qty"=>$item_qty);

or change your code to

$new = "new_name";
$array[0][$new]=$array[0]["Order_no"];
unset($array["Order_no"]);
print_r($array);

Just be careful this would change the order of the array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM