usort closure example (patch by Benjamin Kuz)

git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@325271 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Peter Cowburn 2012-04-17 18:56:19 +00:00
parent 0fbb3e56ae
commit 6863e5d2ab

View file

@ -207,6 +207,41 @@ foreach ($a as $item) {
b
c
d
]]>
</screen>
</example>
<example>
<title>
<function>usort</function> example using a <link linkend="functions.anonymous">closure</link>
to sort a multi-dimensional array
</title>
<programlisting role="php">
<![CDATA[
<?php
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($array, build_sorter('key_b'));
foreach ($array as $item) {
echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
y, a
x, b
z, c
]]>
</screen>
</example>