Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing usort to sort Arrays of Arrays with Arrays PHP
    text
    copied!<p>I have an array of arrays with arrays in PHP and I want to sort the top level of the array based on a field within each element, and I also want to sort an array within each element based on an element of an array of that element. (see example). I want it so that in the end, <code>$data</code> has first the item with the <code>'primary'</code> value of 'first' then 'second'. I also want it so that within 'first' and 'second', the array under the field <code>'secondary'</code> has first the item with the <code>'val'</code> of 'foo' then 'bar' (for both 'first' and 'second') </p> <pre><code>$data = array ( array ( 'myid' =&gt; 4, 'primary' =&gt; 'second', 'secondary' =&gt; array ( array ( 'myid' =&gt; 10, 'val' =&gt; 'bar', ), array ( 'myid' =&gt; 8, 'val' =&gt; 'foo', ), ), ), array ( 'myid' =&gt; 2, 'primary' =&gt; 'first', 'secondary' =&gt; array ( array ( 'myid' =&gt; 10, 'val' =&gt; 'bar', ), array ( 'myid' =&gt; 8, 'val' =&gt; 'foo', ), ), ), ); function mysort($a, $b) { return $a['myid'] &gt; $b['myid']; } echo "pre sort:\n"; print_r($data); usort($data, 'mysort'); echo "post top level sort:\n"; print_r($data); foreach ($data as $k=&gt;$item) { usort($item['secondary'], 'mysort'); echo "Second Level Item sort:\n"; print_r($item['secondary']); } echo "post second level sort:\n"; print_r($data); </code></pre> <p>Why am I getting the following final output?</p> <pre><code>post second level sort: Array ( [0] =&gt; Array ( [myid] =&gt; 2 [primary] =&gt; first [secondary] =&gt; Array ( [0] =&gt; Array ( [myid] =&gt; 10 [val] =&gt; bar ) [1] =&gt; Array ( [myid] =&gt; 8 [val] =&gt; foo ) ) ) [1] =&gt; Array ( [myid] =&gt; 4 [primary] =&gt; second [secondary] =&gt; Array ( [0] =&gt; Array ( [myid] =&gt; 10 [val] =&gt; bar ) [1] =&gt; Array ( [myid] =&gt; 8 [val] =&gt; foo ) ) ) ) </code></pre> <p>By the way I'm using PHP 5.2.17.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload