Home  >  Article  >  Backend Development  >  PHP数组按键降序打印时键值相同只显示一个?

PHP数组按键降序打印时键值相同只显示一个?

WBOY
WBOYOriginal
2016-06-06 20:37:03741browse

<code>php</code><code><?php $age=array("Bill"=>"36","Bill"=>"35","Peter"=>"43");
krsort($age);

foreach($age as $x=>$x_value)
    {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
    }
?>
</code>

回复内容:

<code>php</code><code><?php $age=array("Bill"=>"36","Bill"=>"35","Peter"=>"43");
krsort($age);

foreach($age as $x=>$x_value)
    {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
    }
?>
</code>

刚才换了按值排序打印没问题,
是不是所有的键(包括数据库等)必须唯一?

本来还以为是排序函数的问题,原来是数组本身定义的问题啊,题主打印一下你的数组大小,本来就只有两个元素啊:

<code>php</code><code>$age=array("Bill"=>"35","Bill"=>"32","Peter"=>"43");
echo count($age);

# > 2
</code>

如果数组里面有两个相同的键值的话,那你想 $age["Bill"](假设这两个 key 的 value 不同) 应该输出谁?

所以这不是排序函数的问题。所以一般的话数组里面的键要唯一,否则会发生混乱。

PHP在定义数组时。键是唯一的。如果出来两个相同的索引。后一个加覆盖前一个
详见:
http://php.net/manual/zh/function.array.php

Statement:
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