Anil Sharma
Anil Sharma

Reputation: 491

Search for a value in JSON using php

I have a JSON file in this format:

[
 ["name","purpose","description"],
 ["name2","purpose2","description2"],
 ["name3","purpose3","description3"]
]

Now, I have got the solutions for finding them by key. But, my JSON doesn't have keys. How can I search inside this JSON object to find second element by using "purpose2"? Also, I need to display the second element (i.e. "name2","purpose2","description2").

I used this function, but it's not helping me out.

function searchJson($obj, $value) {
foreach($obj as $item) {
    foreach($item as $child) {
        if(isset($child) && $child == $value) {
            return $child;
        }
    }
}
return null;
}

Thanks in advance !

Upvotes: 0

Views: 5130

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

As the json data doesn't have string keys upon which to search you can branch the logic in the function to test for numeric indexes and then use in_array perhaps

$json = '[["name","purpose","description"],["name2","purpose2","description2"],["name3","purpose3","description3"]]';

function searchJson( $obj, $value ) {
    foreach( $obj as $key => $item ) {
        if( !is_nan( intval( $key ) ) && is_array( $item ) ){
            if( in_array( $value, $item ) ) return $item;
        } else {
            foreach( $item as $child ) {
                if(isset($child) && $child == $value) {
                    return $child;
                }
            }
        }
    }
    return null;
}
$data = json_decode( $json );
$results = searchJson( $data , 'purpose2' );
print_r( $results );

Upvotes: 2

Related Questions