Array search to get key value doesn't work after json_decode

Viewed 380

I have this JSON code:

[
{"id":16385,"value":"2"},
{"id":4121,"value":"Spiderman"},
{"id":78036,"value":"Batman"},
{"id":8075,"value":["I accept the terms"]}
]

I am having this array below out of using json_decode:

Array ( 
[0] => stdClass Object ( [id] => 16385 [value] => 2 ) 
[1] => stdClass Object ( [id] => 4121 [value] => Spiderman ) 
[2] => stdClass Object ( [id] => 78036 [value] => Batman ) 
[3] => stdClass Object ( [id] => 8075 [value] => Array ( [0] => I accept the terms ) ) 
)

I want to use the array_search https://www.php.net/manual/en/function.array-search.php

So I wrote this:

$key = array_search('4121', $array);

I expected $key to be 1 but it is empty if I do echo $key;

Below my complete code:

function personen_tonen() { 
    ob_start();
    global $wpdb;

    //SQL query
    $sql = "SELECT JSON_EXTRACT(custom_fields, '$') AS 'Test' FROM `wp_bookly_customer_appointments`";

    $personen = $wpdb->get_results($sql);   

    foreach($personen as $persoon) {

        $array = $persoon->Test;
        $data = json_decode($array);

        print_r($data);

       $key = array_search('4121', $data);
       echo $key;

    }

    return ob_get_clean();
}
add_shortcode('personen', 'personen_tonen');
2 Answers

You should use array_column to get all the ids otherwise array_search will try to find the object "4121", which is not what you want. Otherwise you can write your own algorithm:

$item = null;
foreach($array as $obj) {
    if ($obj->id == '4121') {
        $item = $obj;
        break;
    }
}

If efficiency is not a concern for you and you won't work with large set of data, use php's algorithm, otherwise consider using this (using array_column you have a O(2*n) complexity, with this solution O(n), so it will be up to 2 times faster)

If you ... want to use the array_search() function, you need to use json_decode() with true as second parameter to decode the JSON string and convert the JSON content into associative arrays:

<?php
$json = '[
   {"id":16385,"value":"2"},
   {"id":4121,"value":"Spiderman"},
   {"id":78036,"value":"Batman"},
   {"id":8075,"value":["I accept the terms"]}
]';

$array = json_decode($json, true);
$key = array_search('4121', array_column($array, 'id'));
$value = array_column($array, 'value');
var_dump($key);
var_dump(array_column($array, 'value')[$key]);
?>
Related