简体   繁体   English

根据多维数组中的键对数组进行排序,并保留其他键值。 的PHP

[英]Sorting an array according to a key in multi dimensional array and preserving other key values. PHP

This is my array. 这是我的数组。

Array
        (
            [Data] => Array
                (
                    [0] => Array
                        (
                            [recipeid] => 108
                            [recipe] => Rasams- the tongue ticklers ! 
                            [image] => No data
                            [category] => Rasams and Soups
                        )

                    [1] => Array
                        (
                            [recipeid] => 44
                            [recipe] => Brain Booster- do you want to try it?
                            [image] => brain-booster-do-you-44-HP-62.jpg
                            [category] => Drinks and Smoothies
                        )

                    [2] => Array
                        (
                            [recipeid] => 36
                            [recipe] => Pineapple Grape Smoothy--a rare combo
                            [image] => pineapple-grape-smoo-36-HP-62.jpg
                            [category] => Drinks and Smoothies
                        )

                )

        )

I have to sort [DATA] array according to alphabetical order of [key]recipe's value, also preserve the recipeid, image, category after sorting. 我必须根据[key]配方值的字母顺序对[DATA]数组进行排序,并且还要在排序后保留配方ID,图像,类别。

You should be able to do this with usort() . 您应该能够使用usort()做到这一点。 Here's an example of how it could be done, based off of the example given in the PHP docs. 这是一个基于PHP文档中给出的示例的示例。

function cmp($a, $b)
{
    if ($a['recipe'] == $b['recipe']) {
        return 0;
    }
    return ($a['recipe'] < $b['recipe']) ? -1 : 1;
}

usort($a, "cmp");

Use usort. 使用usort。

usort($yourarray['Data'], 'data_sort');

function data_sort($a, $b) {
  return (strcasecmp($a['recipe'], $b['recipe']) > 0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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