-1

I'm currently working with Twig. in an array of json can show 3 different types of elements.

"items":[
    {
     "type": "youtube"
    },
    {
     "type": "Picture"
    },
    {
     "type": "Gallery"
    }
]

I want to first select the type youtube in case there is no youtube select picture.

  • What did you try so far? – Wais Kamal Dec 27 '18 at 13:05
  • That's an array of objects and not [JSON](http://json.org) -> [javascript - What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Dec 27 '18 at 13:08

1 Answers1

0

You can use array_column if you use PHP 7+ to flatteren the array and then search it for the value 'youtube'.
If not found then search for 'Picture'.

$arr = json_decode($str, true);

$type = array_column($arr, 'type');
$key = array_search('youtube', $type);

if($key === false){
    $key = array_search('Picture', $type);
}

The return value is the key in $arr that you are looking for.
Like var_dump($arr[$key]);

https://3v4l.org/Cbs1u

Andreas
  • 23,610
  • 6
  • 30
  • 62