Home > php教程 > PHP源码 > PHP 数组排序后,仍保留对应的字符串键名

PHP 数组排序后,仍保留对应的字符串键名

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-02 09:14:17
Original
2098 people have browsed it
跳至 [1] [全屏预览]
<meta charset="utf-8" />
<?php
//一个字符串键名(下标)的数组
$fruits=array("柠檬"=>"lemon","橘子"=>"orange","香蕉"=>"banana",
	"苹果"=>"apple","蓝莓"=>"blueberry","草莓"=>"strawberry",
	"芒果"=>"mango","榴莲"=>"durian","西瓜"=>"watermelon",
	"鸭梨"=>"pear","葡萄"=>"grape");

foreach ($fruits as $key => $val) //输出原始数组 $fruits
    echo  "fruits[".$key."] = ".$val."<br/>";
	echo "<hr color=red>";

// 调用 sort_with_keyName()方法, 获得 排好序的数组
	$fruits_sorted = sort_with_keyName( $fruits);
//输出最终结果。
	foreach($fruits_sorted as $key=>$val)
echo "fruites sorted[".$key."] = ".$val."<br/>";

/* 定义一个对数组 $arr 实施排序, 
 * 同时保留对应的字符串键名 (下标) 的排序方法
 */
function sort_with_keyName( $arr) {
//在内存的另一处 $a 复制内容与 $arr 一样的数组
	foreach($arr as $key => $value) 
	$a[$key]=$value;
	sort($arr); //对数组 $arr 进行排序

/*创建一个以原始数组的键名为元素值 (键值) 的
 *数组 $b, 其元素 (键值) 顺序,与排好序的数组 $arr 一致。
*/
	$index=0;
 	foreach ($arr as $keys => $values) //按排序后数组的顺序
 	foreach($a as $key => $value) //在备份数组中寻找键值
 	if ($values==$value)//如果找到键值
 	$b[$index++]=$key; // 则将数组 $b 的元素值,设置成备份数组 $a 的键名 
//返回用数组 $b 的键值作为键名,数组 $arr 的键值作为键值,所组成的数组 
	return array_combine($b, $arr);
};
?>
Copy after login

2. [图片] Array_With_String_Keys.png    

PHP 数组排序后,仍保留对应的字符串键名
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template