猿问

PHP重命名关联数组中的键

我一直在搜索关于这个问题的 SO 文章,并在我自己的代码中尝试了许多解决方案,但它似乎不起作用。


我有以下数组


$array[] = array("Order_no"=>$order_id,

                "Customer"=>$customer_id,

                "Product"=>$code_po,

                "Product_description"=>$code_description,

                "Position"=>$pos,

                "Qty"=>$item_qty

                );

我希望用数据库查询中的变量替换“Order_no”键,假设在这种情况下变量是“new_name”


$new = "new_name";

$array[$new]=$array["Order_no"];

unset($array["Order_no"]);

print_r($array);

在 print_r 语句中,我得到了 new_name 作为正确的订单号,但我仍然在那里看到“Order_no”,我不应该再看到了。


慕丝7291255
浏览 148回答 4
4回答

慕妹3242003

这是你的数组:Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Customer] => 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Product] => 99&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Order_no] => 12345&nbsp; &nbsp; &nbsp; &nbsp; ))一种方法:<?php$arr[] = [&nbsp; &nbsp; "Order_no" => 12345,&nbsp; &nbsp; "Customer" => 00002,&nbsp; &nbsp; "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);另一种方式:<?php$arr[] = [&nbsp; &nbsp; "Order_no" => 12345,&nbsp; &nbsp; "Customer" => 00002,&nbsp; &nbsp; "Product"=> 99];$arr[0]["new_name"] = $arr[0]["Order_no"];unset($arr[0]["Order_no"]);print_r($arr);随时展平您的阵列:<?php$arr = $arr[0];print_r($arr);

神不在的星期二

您正在使用额外级别的数组(通过执行$array[] = ...)。您应该将其[0]作为第一个索引来执行:$array[0][$new]=$array[0]["Order_no"];unset($array[0]["Order_no"]);现场示例:3v4l另一种选择是跳过这个额外的级别并将数组初始化为:$array = array("Order_no"=>$order_id, ...

冉冉说

$array也是一个数组,你必须使用索引:&nbsp;&nbsp;&nbsp;&nbsp;$array[0][$new]=$array[0]["Order_no"]; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unset($array[0]["Order_no"]);

芜湖不芜

其他答案将在您第一次添加到数组时起作用,但它们始终适用于数组中的第一项。一旦你添加另一个它就不起作用了,所以获取当前密钥:$array[key($array)][$new] = $array[key($array)]["Order_no"];unset($array[key($array)]["Order_no"]);如果你想要第一个,那么reset($array);先打电话。
随时随地看视频慕课网APP
我要回答