给出以下数组:
$ arr =数组([0] =>“ apple”,[1] =>“菠萝”,[2] =>“水果”);
如何将“水果”(如果存在于数组中)放置到第一个索引上,从而将其他水果向前推?
预期结果:
$arr = array ([0] => "fruit", [1] => "apple", [2] => "pineapple");
答案 0 :(得分:1)
尝试使用array_search()
和array_unshift()
<?php
$arr = array ("apple","pineapple","fruit");
$fruit_key = array_search('fruit', $arr);
if($fruit_key){
$fruit_value = $arr[$fruit_key];
unset($arr[$fruit_key]);
array_unshift($arr, $fruit_value);
print_r($arr);
}
?>
输出:
Array (
[0] => fruit
[1] => apple
[2] => pineapple
)