![](/img/trans.png)
[英]What would be the best way to implode this associative array with keys and values
[英]What is the best way to move an associative array index to a different location
可以說我們有以下數組
$myArray = array(
"foo" => "value1" ,
"bar" => "value2" ,
"baz" => "value3" ,
"qux" => "value4"
);
當循環遍歷並回顯每個值時,它總是會先打印foo,然后打印bar,然后顯示baz,最后打印qux。 可以說我想在foo之后顯示qux的值。 做這個的最好方式是什么。 我正在嘗試所有不同的usort,uasort,uksort,但沒有得到我想要的東西。
我看到了很多很好的代碼,可以使用splice將索引移到頂部,但沒有找到最好的方法,該如何在關聯數組的另一個索引之前移動該索引呢?我們遍歷它,我們先找到我們想要的索引。
像這樣嗎
function custom_compare($a, $b) {
$target = array('foo', 'qux', 'bar', 'baz');
return array_search($b, $target) - array_search($a, $target);
}
$myArray = array(
"foo" => "value1",
"bar" => "value2",
"baz" => "value3",
"qux" => "value4"
);
uksort($myArray, 'custom_compare');
不是很優雅,但是可以用:
$arr = array(
"foo" => "value1" ,
"bar" => "value2" ,
"baz" => "value3" ,
"qux" => "value4"
);
$tmp = array();
foreach($arr as $k=>$v) {
$tmp[] = array($k=>$v);;
}
array_splice($tmp, 1, 0, array_slice($tmp, 3));
array_splice($tmp, -1);
$arr = array();
foreach($tmp as $k => $v) {
foreach($v as $k2 => $v2) {
$arr[$k2] = $v2;
}
}
print_r($arr);
輸出:
Array
(
[foo] => value1
[qux] => value4
[bar] => value2
[baz] => value3
)
也許您可以使用這樣的東西?
沒有所有的PHP-$
function swap(arr, idxFrom, idxTo )
{
var tmp = arr[idxFrom];
arr[idxFrom] = arr[idxTo];
arr[idxTo] = tmp;
}
抱歉,這應該被低估:您可以在數組中找到參數的索引,然后使用拼接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.