Note that there are some explanatory texts on larger screens.

plurals
  1. POUnwanted behavior of PHP usort
    text
    copied!<p>I have a problem with PHP <code>usort()</code>. Let's suppose I have an array like this (that's a simplification, I've not to work with names, and I have an array of objects, not arrays):</p> <pre><code>$data = array( array('name' =&gt; 'Albert', 'last' =&gt; 'Einstein'), array('name' =&gt; 'Lieserl', 'last' =&gt; 'Einstein'), array('name' =&gt; 'Alan', 'last' =&gt; 'Turing' ), array('name' =&gt; 'Mileva', 'last' =&gt; 'Einstein'), array('name' =&gt; 'Hans Albert', 'last' =&gt; 'Einstein') ); </code></pre> <p>As you can see, the array is sorted arbitrarily.</p> <p>Now, if want to sort it by <code>last</code>, I do:</p> <pre><code>function sort_some_people($a, $b) { return strcmp($a['last'], $b['last']); } usort($data, 'sort_some_people'); </code></pre> <p>And I have:</p> <pre><code>Array ( [0] =&gt; Array ( [name] =&gt; Mileva [last] =&gt; Einstein ) [3] =&gt; Array ( [name] =&gt; Albert [last] =&gt; Einstein ) [1] =&gt; Array ( [name] =&gt; Lieserl [last] =&gt; Einstein ) [2] =&gt; Array ( [name] =&gt; Hans Albert [last] =&gt; Einstein ) [4] =&gt; Array ( [name] =&gt; Alan [last] =&gt; Turing ) ) </code></pre> <p>That is ok, now they are sorted by <code>last</code>. But, as you can see, I've just completely lost the previous sorting. What am I saying? I want to preserve array sorting as it was before, but as a <em>secondary</em> sorting. I hope I was clear. <strong>Practically</strong> I want to sort data using something as <code>usort()</code> (so, a completely custom sorting), but if sorting field is identical between two items, I want to keep their <em>relative position</em> as it was before. Considering the given example, I want <code>Lieserl Einstein</code> to appear before <code>Mileva Einstein</code> because it was like this at beginning.</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