PHP从一开始就获取数组键和值,并将其放在末尾



我有一个具有literal_key=>值的PHP数组。我需要将键和值从数组的开头移开,并将其粘贴在末尾(也保留键)。

我试过:

$f = array_shift($fields);
array_push($fields, $f);

但这会丢失关键值。例如:

$fields = array ("hey" => "there", "how are" => "you");

//运行高于

这就产生了:

$fields = array ("how are" => "you", "0" => "there");

(我需要保持"嘿"而不是0)有什么想法吗?

据我所知,不能用array_push()向数组添加关联值,也不能用array_shift()获取键。(pop/push也是如此)。一个快速破解可能是:

$fields = array( "key0" => "value0", "key1" => "value1");
//Get the first key
reset($fields);
$first_key = key($fields);
$first_value = $fields[$first_key];
unset($fields[$first_key]);
$fields[$first_key] = $first_value;

看它在这里工作。一些源代码取自https://stackoverflow.com/a/1028677/1216976

您可以使用array_keys获取第0个密钥$key,然后使用array_shift设置$value,然后设置$fields[$key] = $value

或者你可以做一些像这样的花哨的事情

array_merge( array_slice($fields, 1, NULL, true),
             array_slice($fields, 0, 1, true)     );

这是未经测试的,但有正确的想法。

最新更新