Skip to content
Advertisement

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

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

Advertisement

Answer

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]);
?>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement