Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get json and sort with multiple arguments [closed]

Tags:

json

php

Well, my question are complicated.

I have that json file:

{
"books": [
    {
        "book": [
            {
                "Title": "Java How to Program",
                "Author": "Deitel & Deitel",
                "Edition": "2007"
            }
        ]
    },
    {
        "book": [
            {
                "Title": "Patterns of Enterprise Application Architecture",
                "Author": "Martin Fowler",
                "Edition": "2002"
            }
        ]
    },
    {
        "book": [
            {
                "Title": "Head First Design Patterns",
                "Author": "Elisabeth Freeman",
                "Edition": "2004"
            }
        ]
    },
    {
        "book": [
            {
                "Title": "Internet & World Wide Web: How to Program",
                "Author": "Deitel & Deitel",
                "Edition": "2007"
            }
        ]
    }
]

}

In my PHP i have this:

    $file = file_get_contents('books.json');
    $json = json_decode($file, true);

How can i sort my array by multiples rules? For example:

echo sort_my_array('Title', ASC, 'Author', DESC, $json);

I've tried in so many ways but i think my error is at when i try to use the array_multidimensional.

Can someone explain to me how to create this?

Thanks in advance

like image 544
Alexandre Avatar asked Mar 02 '26 03:03

Alexandre


1 Answers

try this

    $file = file_get_contents('books.json');
    $json = json_decode($file, true);
   $json = array_map(function($a) { return $a['book'][0]; }, $json['books']);
 foreach ($json as $key => $row) {
    $title[$key] = $row['Title'];
   $author[$key] = $row['Author'];
 }
 array_multisort($title, SORT_ASC,  $author, SORT_DESC, $json);
 echo "<pre>";
 print_r($json);
 echo "</pre>";

I have tried it and its working

like image 172
alwaysLearn Avatar answered Mar 04 '26 18:03

alwaysLearn