John Davidson

arrays - get all similar keys in JSON object in PHP


let say, i have this JSON data i want to print all key by name "id", what should i do?

$json = {"response":[
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"

i tried this but this one is only giving me first array object sub key(which is id=37) i want all like (id=37, id=38)

$op =  $json->{'response'}[0]->{'id'};

My Answer:
You can achieve this by decoding the JSON data into an associative array in PHP and then iterating over the keys to find all keys with a specific name. Here's an example code snippet to demonstrate this:

$jsonData = '{
"name": "John",
"age": 30,
"city": "New York",
"name": "Jane",
"occupation": "Engineer",
"name": "Alice"

$data = json_decode($jsonData, true);

$searchKey = 'name';
$keys = array_keys($data, $searchKey);

foreach ($keys as $key) {
echo $key . PHP_EOL;

In this example, the JSON data contains multiple keys with the name "name". We decode the JSON data into an associative array and then use the `array_keys` function to find all keys with the name "name". Finally, we iterate over the keys and print them out.

Rate this post

3 of 5 based on 6139 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us