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

时间:2011-10-14 04:54:31

标签: php arrays sorting multidimensional-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
                        )

                )

        )

我必须按照[key]食谱值的字母顺序对[DATA]数组进行排序,并在排序后保留recipeid,image,category。

2 个答案:

答案 0 :(得分:0)

您应该可以使用usort()执行此操作。以下是基于PHP文档中给出的示例的如何完成的示例。

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

usort($a, "cmp");

答案 1 :(得分:0)

使用usort。

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

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