按定义的值列表

时间:2017-03-29 05:11:38

标签: php arrays

好的,我确信这已经在某个地方得到了解答我为发布这样一个基本问题而道歉,但我似乎无法在任何地方找到答案......我只是在蘸我的第一次进入php的大脚趾,把大部分时间花在Javascript上,所以对我很好: - )

我有一组具有以下结构的对象:

[
  {
    title: 'one',
    type: 'cat'
  },
  {
    title: 'two',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'four',
    type: 'dog'
  }
]

我想按照['dog', 'snake', 'cat]的顺序订购它们,所以我得到了:

[
  {
    title: 'two',
    type: 'dog'
  }
  {
    title: 'four',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'one',
    type: 'cat'
  }
]

我该怎么做?

2 个答案:

答案 0 :(得分:0)

PHP code demo

<?php
ini_set("display_errors", 1);
$json ='[
  {
    "title": "one",
    "type": "cat"
  },
  {
    "title": "two",
    "type": "dog"
  },
  {
    "title": "three",
    "type": "snake"
  },
  {
    "title": "four",
    "type": "dog"
  }
]';
$dataArray=json_decode($json,true);
$sortFormat=['dog', 'snake', 'cat'];
$result=array();
while(count($dataArray)>0)
{
    foreach($sortFormat as $object)
    {
        foreach($dataArray as $key => $objectData)
        {
            if($objectData["type"]==$object)
            {
                $result[]=$objectData;
                unset($dataArray[$key]);
            }
        }
    }
}
print_r($result);

<强>输出:

Array
(
    [0] => Array
        (
            [title] => two
            [type] => dog
        )

    [1] => Array
        (
            [title] => four
            [type] => dog
        )

    [2] => Array
        (
            [title] => three
            [type] => snake
        )

    [3] => Array
        (
            [title] => one
            [type] => cat
        )

)

答案 1 :(得分:0)

$order = array_flip(['dog', 'snake', 'cat']);

usort($data, function($a, $b) use($order) {
    $aType = $a->type;
    $bType = $b->type;

    if (!isset($order[$aType]) && !isset($order[$bType])) {            
        return strcmp($aType, $bType);
    }
    $aOrder = $order[$aType] ?? 0;
    $bOrder = $order[$bType] ?? 0;

    return $aOrder - $bOrder;
});

修改:如果您确定“类型”只能是['dog', 'snake', 'cat']中的一个,则可以简化它:

usort($data, function($a, $b) use($order) {
    return $order[$a->type] - $order[$b->type];
});