1

Ok, I am sure that this has already been answered somewhere and I apologise for posting such a fundamental question, but I can't seem to find the answer anywhere... I'm only just dipping my big toe into php for the first time and spend most of my time in Javascript, so be nice to me :-)

I have an array of objects that is of the structure:

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

And I'd like to order them in the order ['dog', 'snake', 'cat] so I get:

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

How do I do this?

oldo.nicho
  • 1,582
  • 1
  • 18
  • 29

2 Answers2

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);

Output:

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
        )

)
Sahil Gulati
  • 14,401
  • 4
  • 20
  • 39
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;
});

Edit: if you know for sure 'type' could only be one of the ['dog', 'snake', 'cat'] you could simplify it:

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