Here, there is such an array

$material_weights = array( 0 => array( 'nid' => 54545, 'weight' => 0 ), 1 => array( 'nid' => 545, ), 2 => array( 'nid' => 225, 'weight' => 4 ), 3 => array( 'nid' => 6, 'weight' => 1 ), 4=> array( 'nid' => 6, ), 5 => array( 'nid' => 6, 'weight' => 3 ), ) 

It is necessary to sort it by the 'weight' field, in ascending order, so that all elements that do not have the 'weight' field are put to the end. But it is better to retain their original sequence, that is, 1 and 6 elements should be inserted at the end, but 1 should still go before 6

    3 answers 3

    If the order of elements that do not have a 'weight' field is not important:

     usort($material_weights, function($a, $b) { return ($a['weight'] ?? null) <=> ($b['weight'] ?? null); }); 

    If it is important to maintain order:

     //array_filter сохраняет ключи $have_not_weight = array_filter($material_weights, function($val) { return !isset($val['weight']); }); $material_weights = array_diff_key($material_weights, $have_not_weight); usort($material_weights, function($a, $b) { return ($a['weight'] ?? null) <=> ($b['weight'] ?? null); }); $material_weights = array_merge($material_weights, $have_not_weight); 

      Well, something like this is probably -

       usort($material_weights, function($a, $b) { if(isset($a['weight'])&&isset($b['weight'])) { return $a['weight'] <=> $b['weight']; // return $a['weight'] - $b['weight']; } elseif(!isset($a['weight'])) { return 1; } elseif(!isset($b['weight'])) { return -1; } }); 

      The second part of the question did not understand.

       Array ( [0] => Array ( [nid] => 54545 [weight] => 0 ) [1] => Array ( [nid] => 6 [weight] => 1 ) [2] => Array ( [nid] => 6 [weight] => 3 ) [3] => Array ( [nid] => 225 [weight] => 4 ) [4] => Array ( [nid] => 6 ) [5] => Array ( [nid] => 545 ) ) 
      • Wrong. It was meant that those elements that do not have weight should not just stand at the end, but remain in the same order, that is, elements with index 1 and 4 should be at the very end, but the element that had index 1 should still to be before the element with the index 4. Your answer is almost what is needed, only the former 4 is standing before the former 1 - Evgeny Shevtsov

      The easiest way is to go through the whole array and sort the elements according to your needs. If the array element does not contain weight , then cut this element into the new array1 and so on, go to the very end of your current array. When all elements are sorted, then all the contents from array1 returned to the array .

      You can do everything without a second array using several if-else

      • Suggest an answer?) Until I even understand my own sorting. let alone to cut and paste back ... - Evgeny Shevtsov
      • I am not familiar with php at all) But I see an algorithm by which this can be done. I wrote it to you above. And, a little search on your topic gives 2 excellent examples, such as this and this - Dred