PHP array check if value in specific key exists -
i using php 5.5.12
.
i have following multidimensional array:
[ { "id": 1, "type":"elephant", "title":"title of elephant" }, { "id": 2, "type":"tiger", "title":"title of tiger" }, { "id": 3, "type":"lion", "title":"title of lion", "children":[{ "id": 4, "type":"cow", "title":"title of cow" }, { "type":"elephant", "title":"title of elephant" }, { "type":"buffalo", "title":"title of buffalo" }] } ]
i iterating array using foreach
loop.
the array key type
must in elephant
, tiger
, lion
. if not, result should return false
.
how can achieve this?
since you're using php5.5.12, can make use of array_column
.
$arr = json_decode($json, true); //walk through each element, paying attention type array_walk( array_column($arr, 'type'), function($element, $k) use(&$arr) { $arr[$k]['valid_type'] = in_array($element, array('lion', 'tiger', 'elephant')); });
from here, each element in array ($arr
) have new key valid_type
boolean value - 1
if type valid, 0
if isn't.
Comments
Post a Comment