PHP |向上或向下移动(键,值)对的程序
给定一个包含键值对的数组,我们需要使用键将特定值向上或向下移动。
例子:
Input : $continents = array(
'First' => 'Asia',
'Second' => 'Europe',
'Third' => 'North America',
'Fourth' => 'South America',
);
move_to_up($continents, 'Third');
Output : Array
(
[Third] => North America
[First] => Asia
[Second] => Europe
[Fourth] => South America
)
Input :$continents = array(
'First' => 'Asia',
'Second' => 'Europe',
'Third' => 'North America',
'Fourth' => 'South America',
);
move_to_bottom($continents, 'Second');
Output : Array
(
[First] => Asia
[Third] => North America
[Fourth] => South America
[Second] => Europe
)
使用下面描述的PHP函数可以解决上述问题:
unset() :函数销毁指定的变量。
方法:我们准备一个带有指定键的临时数组(值要上移或下移),然后取消设置键,最后根据将值上移或下移的目的附加。
下面是方法的实现
代码 1:移动键,值在顶部
'Asia',
'Second' => 'Europe',
'Third' => 'North America',
'Fourth' => 'South America',
);
move_to_up($continents, 'Third');
print_r ($continents);
function move_to_up(&$continents, $string)
{
$var = array($string => $continents[$string]);
unset($continents[$string]);
$continents = $var + $continents;
}
?>
输出:
Array
(
[Third] => North America
[First] => Asia
[Second] => Europe
[Fourth] => South America
)
代码2:移动键,底部的值
'Asia',
'Second' => 'Europe',
'Third' => 'North America',
'Fourth' => 'South America',
);
move_to_bottom($continents, 'Second');
print_r ($continents);
function move_to_bottom(&$continents, $string)
{
$var = array($string => $continents[$string]);
unset($continents[$string]);
$continents = $continents + $var;
}
?>
输出:
Array
(
[First] => Asia
[Third] => North America
[Fourth] => South America
[Second] => Europe
)