我有一个数组,我正在从另一个源检索,键是预置字符串。我使用$devices作为我要检索的数组的示例。
我想用1比1匹配的$devices替换$new_keys的键名。下面的代码是我到目前为止所得到的,但我没有得到我正在寻找的结果?
$devices = array('uniqueId' => '1234','status' => 'online','lastUpdate' => time(),'phone' => '1234','model' => 'test','contact' => 'admin'
$new_keys = array('IMEI','Status','Last Update','Phone','Model','Contact');
for ($i = 0; $i < count($devices) - 1; $i++) {
array_replace($devices[$i], $new_keys[$i]);
}谢谢!
发布于 2017-03-22 10:48:58
请看一下PHP函数array_combine()。它能满足你的需要:
$devices = array('uniqueId' => '1234','status' => 'online','lastUpdate' => time(),'phone' => '1234','model' => 'test','contact' => 'admin');
$new_keys = array('IMEI','Status','Last Update','Phone','Model','Contact');
$fixed = array_combine($new_keys, array_values($devices));
// print_r($fixed);产出:
Array
(
[IMEI] => 1234
[Status] => online
[Last Update] => 1490179692
[Phone] => 1234
[Model] => test
[Contact] => admin
)发布于 2017-03-22 10:49:42
array_replace将替换键匹配的值,而不是键本身。
最好是创建一个新数组,并将这两个数组合并到您的循环中。您需要将for替换为foreach,而且您也不能使用$i引用(我不认为) $devices数组。
$devices = array('uniqueId' => '1234','status' => 'online','lastUpdate' => time(),'phone' => '1234','model' => 'test','contact' => 'admin'
$new_keys = array('IMEI','Status','Last Update','Phone','Model','Contact');
$new_devices = array();
$i = 0;
foreach($devices as $key => $value) {
$new_devices[$new_keys[$i]] = $value;
$i++;
}我不知道你到底在这里做什么,但使用这种1比1的新旧键的关系,基于他们的位置,是自找麻烦!
发布于 2017-03-22 10:48:27
$newArr = array();
for ($i = 0; $i < count($devices) - 1; $i++) {
$newArr[$new_keys[$i]]=$devices[$i];
}
$device = $newArr;https://stackoverflow.com/questions/42949228
复制相似问题