简体   繁体   中英

How to sort php multidimensional array

How to sort php array by second key or how to reformat that array to make it possible I want to order array by 1,2 (second key)

( [0] => Array ( [1] => Array ( [hashtag] => a7e87329b5eab8578f4f1098a152d6f4 [title] => Flower [order] => 3 ) )

[1] => Array
    (
        [2] => Array 
            (
            [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
            [title] => Free
            [order] => 2
            )
    )

[2] => Array
    (
        [1] => Array 
            (
            [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
            [title] => Ready
            [order] => 1
            )
    )

[3] => Array
    (
        [2] => Array 
            (
            [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
            [title] => Ready
            [order] => 1
            )
    )

)

<?

function sorting($arr) {
  for ($i=0; $i < count($arr); $i++) {
    for ($j=0; $j < count($arr)-$j-1; $j++) {
      if (key($arr[$j]) > key($arr[$j+1])) {
        $tmp = $arr[$j];
        $arr[$j] = $arr[$j+1];
        $arr[$j+1] = $tmp;
      }
    }
  }

  return $arr;
}

$testArray = array(
  0 => array(
        2 => array
            (
            "hashtag" => "b24ce0cd392a5b0b8dedc66c25213594",
            "title" => "Free",
            "order" => 2
            )
    ),
  1 => array(
        1 => array
            (
            "hashtag" => "e7d31fc0602fb2ede144d18cdffd816b",
            "title" => "Ready",
            "order" => 1
            )
    ),
  2 => array(
        2 => array
            (
            "hashtag" => "e7d31fc0602fb2ede144d18cdffd816b",
            "title" => "Ready",
            "order" => 1
            )
    ));

echo var_dump(sorting($testArray));

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM