Continuing the theme . You need to make a function so that other users can sort by the field they need. I do it like this:

function sort_page($pages,$field,$sort) { usort($pages,function($a,$b) { return ($a[$field] - $b[$field]); }); return $pages; } 

In the template I call as follows:

 {$pages = sort_page($pages,'field_price','desc')} 

I send an array, the field by which you want to sort, and the sort order (in the example is not used). If i write

 return ($a['field_price'] - $b['field_price']); 

Then everything works fine, if as in the example, it does not work. As if the function inside usort does not accept other variables. How to be?

    2 answers 2

    Try this:

     function sort_page($pages,$field,$sort) { usort($pages,function($a,$b)use($field) { return ($a[$field] - $b[$field]); }); return $pages; } 

    In PHP, the closure of variables to an anonymous function must be specified explicitly through use .

    • And this is the correct answer! Thank you very much! - chuikoff

    We look at the work of the code here (To start, click " Run ")

     $data = array( array('name' => 'title 1','price' => '200'), array('name' => 'title 2','price' => '100'), array('name' => 'title 3','price' => '500'), array('name' => 'title 4','price' => '30') ); foreach ($data as $key => $row) { $name[$key] = $row['name']; $price[$key] = $row['price']; } array_multisort($price, SORT_NUMERIC, $name, $data); echo '<pre>'; print_r($data); echo '</pre>'; 
    • It's all good, but my array is not the same, there are still a lot of fields. name and price I made for example. I'm just wondering why the variable is not readable in that function. Maybe it should make a global or something else? - chuikoff