简体   繁体   中英

How can I sort a PHP multidimensional array by the value of one of its keys?

I have a multidimensional array of database values. The titles are stored in language files, so I cannot simply order the db query by title.I have to loop through the results and get the title from a language file based on the id of the category. Because of this, I have to create a custom array with the appropriate title.

This is from my model:

<?php
function retrieve(){

    foreach($query_cats->result_array() as $cat){

        $info[] = array(
            'id' => $cat['id'],
            'title' => $this->lang->line('cat_'.$cat['id']),
            'slug' => $cat['slug'],
            'icon' => $cat['icon']
        );

    }

    return $info;

}

Is there a php function that will allow me to sort the $info array by the value of the title key? I wasn't sure how I could do this with asort($info) since the array is more complicated.

I'm Not sure if this what you want, But you could dige more in this function array_multisort() or use the following example to make you own code.

$title= array();
foreach ($info as $key => $row)
{
    $title[$key] = $row['title'];
}
array_multisort($price, SORT_DESC, $info);

You could use usort in combination with strcasecmp . I also propose a simplification in the loop in your function:

function retrieve(){
    foreach ($query_cats->result_array() as $cat) {
        $cat['title'] = $this->lang->line('cat_'.$cat['id']);
        $info[] = $cat;
    }
    usort($info, function($a, $b) {
        return strcasecmp($a['title'], $b['title']);
    });
    return $info;
}

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