如何从关联数组中提取元素?
$array = array(
"smart" => "dog",
"stupid" => "cat",
"nasty" => "frog",
"big" => "elephant"
);
我需要删除带有“nasty”键的元素,将其推送到数组的末尾。我不知道数组中元素的索引。我怎样才能做到这一点? (我使用的是第一个,第二个,第三个,但是键的名称是不同的,没有用逻辑索引!我需要通过它的键删除元素。)
答案 0 :(得分:2)
尝试:
$array = array(
"first" => "un",
"second" => "dos",
"third" => "tres"
);
$second = $array['second'];
unset($array['second']);
$array['second'] = $second;
输出:
array(3) {
["first"]=>
string(2) "un"
["third"]=>
string(4) "tres"
["second"]=>
string(3) "dos"
}
修改强>
$array = array(
"first" => "un",
"second" => "dos",
"third" => "tres"
);
$output = array();
$order = array('first', 'third', 'second');
foreach ( $order as $key ) {
if ( isset($output[$key]) ) {
$output[$key] = $array[$key];
}
}
答案 1 :(得分:1)
$array = array(
"smart" => "dog",
"stupid" => "cat",
"nasty" => "frog",
"big" => "elephant"
);
$array += array_splice($array, array_search('nasty', array_keys($array)), 1);
print_r($array);
答案 2 :(得分:0)
extract($array);
怎么样?