Home > Net >  Sort multidimensional array by specific key value
Sort multidimensional array by specific key value

Time:03-01

I'm working on algorithm to display my events on the website. I want to sort my multidimensional array by specific key value.

My array:

    ["2022-02-28"]=>
  array(1) {
    [0]=>
    array(3) {
      ["post_id"]=>
      string(4) "3656"
      ["time"]=>
      string(5) "16:05"
      ["priority"]=>
      string(1) "0"
    }
  }
  ["2022-03-01"]=>
  array(2) {
    [2]=>
    array(3) {
      ["post_id"]=>
      string(4) "3656"
      ["time"]=>
      string(5) "16:05"
      ["priority"]=>
      string(1) "0"
    }
    [3]=>
    array(3) {
      ["post_id"]=>
      string(4) "3784"
      ["time"]=>
      string(5) "13:00"
      ["priority"]=>
      string(1) "0"
    }
  }
  ["2022-03-03"]=>
  array(1) {
    [5]=>
    array(3) {
      ["post_id"]=>
      string(4) "3663"
      ["time"]=>
      string(5) "13:06"
      ["priority"]=>
      string(1) "1"
    }
  }
}

I want to sort the array by "time" key value. So for example at this index :

    ["2022-03-01"]=>
  array(2) {
    [2]=>
    array(3) {
      ["post_id"]=>
      string(4) "3656"
      ["time"]=>
      string(5) "16:05"
      ["priority"]=>
      string(1) "0"
    }
    [3]=>
    array(3) {
      ["post_id"]=>
      string(4) "3784"
      ["time"]=>
      string(5) "13:00"
      ["priority"]=>
      string(1) "0"
    }
  }

I want first 13:00 to appear then 16:05. Thank you for your help in advance! :)

CodePudding user response:

Use usort for define custom sort.

function time_sort(array $arr){
  usort($arr, function($a, $b){
    return strcmp($a['time'], $b['time']);
  });
}

CodePudding user response:

Try with this:

<?php 


$arr = array();

$arr["2022-02-28"] = [
    array("post_id"=>"3656", "time"=>"16:05", "priority"=>"0"),
    array("post_id"=>"4856", "time"=>"13:05", "priority"=>"3")];
$arr["2022-03-01"] = [
    array("post_id"=>"3656", "time"=>"16:05", "priority"=>"0"),
    array("post_id"=>"3636", "time"=>"13:05", "priority"=>"1")
    ];



foreach($arr as $key => $value){
    
   usort($value, function($a,$b){
       return strtotime($a["time"])>strtotime($b["time"]);
    });
         
    $arr[$key] = $value;  

}

echo "<pre>";
var_dump($arr);
echo "</pre>";

Output:

array(2) {
["2022-02-28"]=>
array(2) {
  [0]=>
  array(3) {
    ["post_id"]=>
    string(4) "4856"
    ["time"]=>
    string(5) "13:05"
    ["priority"]=>
    string(1) "3"
  }
  [1]=>
  array(3) {
    ["post_id"]=>
    string(4) "3656"
    ["time"]=>
    string(5) "16:05"
    ["priority"]=>
    string(1) "0"
  }
}
["2022-03-01"]=>
array(2) {
  [0]=>
  array(3) {
    ["post_id"]=>
    string(4) "3636"
    ["time"]=>
    string(5) "13:05"
    ["priority"]=>
    string(1) "1"
  }
  [1]=>
  array(3) {
    ["post_id"]=>
    string(4) "3656"
    ["time"]=>
    string(5) "16:05"
    ["priority"]=>
    string(1) "0"
  }
}
  • Related