Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP sort array with three variables
    text
    copied!<p>I need help sorting an associative array with PHP.</p> <p>The sorting should rely on the array key "name", and keep the key/value pairs. Following sorting order: 1) first <em>integer</em> ASC, 2) second <em>integer</em> ASC, 3) third <em>mixed</em> ASC </p> <p><strong>input</strong></p> <pre><code>array(6) { [0]=&gt; array(2) { ["name"]=&gt; string(13) "60 to 90 in 6" ["timing"]=&gt; float(4.7) } [1]=&gt; array(2) { ["name"]=&gt; string(15) "40 to 120 in KD" ["timing"]=&gt; float(3.3) } [2]=&gt; array(2) { ["name"]=&gt; string(14) "60 to 100 in 4" ["timing"]=&gt; float(1.5) } [3]=&gt; array(2) { ["name"]=&gt; string(13) "60 to 90 in 4" ["timing"]=&gt; float(2.4) } [4]=&gt; array(2) { ["name"]=&gt; string(15) "140 to 160 in 6" ["timing"]=&gt; float(2.4) } [5]=&gt; array(2) { ["name"]=&gt; string(13) "60 to 90 in KD" ["timing"]=&gt; float(5.7) } } </code></pre> <p><strong>output order</strong></p> <p><code>1, 3, 0, 5, 2, 4</code></p> <p>Thank you very much for your help.</p> <hr> <h1>Answer:</h1> <pre><code>uasort($acceleration, function($a, $b) { if($a['_sort'][0] == $b['_sort'][0] AND $a['_sort'][2] == $b['_sort'][2]) { if($a['_sort'][4] &lt; $b['_sort'][4]) return -1; elseif($a['_sort'][4] &gt; $b['_sort'][4]) return 1; else return 0; } elseif($a['_sort'][0] == $b['_sort'][0]) { if($a['_sort'][2] &lt; $b['_sort'][2]) return -1; elseif($a['_sort'][2] &gt; $b['_sort'][2]) return 1; return 0; } else { if($a['_sort'][0] &lt; $b['_sort'][0]) return -1; elseif($a['_sort'][0] &gt; $b['_sort'][0]) return 1; else return 0; } }); </code></pre> <p>I'm sure, there is a more elegant way, but may serve as input.</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