Asked  7 Months ago    Answers:  5   Viewed   38 times

I have a JSON array

{
  "people":[
    {
      "id": "8080",
      "content": "foo"
    },
    { 
      "id": "8097",
      "content": "bar"
    }
  ]
}

How would I search for 8097 and get the content?

 Answers

48

Use the json_decode function to convert the JSON string to an array of object, then iterate through the array until the desired object is found:

$str = '{
  "people":[
    {
      "id": "8080",
      "content": "foo"
    },
    { 
      "id": "8097",
      "content": "bar"
    }
  ]
}';

$json = json_decode($str);
foreach ($json->people as $item) {
    if ($item->id == "8097") {
        echo $item->content;
    }
}
Wednesday, March 31, 2021
 
turson
answered 7 Months ago
74

You want array_keys with the search value

array_keys($list[0], "2009-09-09");

which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with array_unique, then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like...

$uniqueKeys = array_unique($list[0])

foreach ($uniqueKeys as $uniqueKey)
{
  $v = array_keys($list[0], $uniqueKey);

  if (count($v) > 1)
  {
    foreach ($v as $key)
    {
      // Work with $list[0][$key]
    }

  }
}
Wednesday, March 31, 2021
 
francadaval
answered 7 Months ago
29

Just to show an alternative syntax to @GuillaumeSTLR answer.

<?php foreach ($array as $location => $items) : ?>

    <strong><?php echo $location ?></strong>

    <?php foreach ($items as $item) : ?>
        <p><?php echo $item ?></p>
    <?php endforeach; ?>


<?php endforeach; ?>

Hope this helps!

Saturday, May 29, 2021
 
Ultimater
answered 5 Months ago
94

You could use json_decode to decode the already encoded field and then add the result in the $res array.

Saturday, May 29, 2021
 
LukeP
answered 5 Months ago
43

If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.

Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:

Example:

// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
  2 => array("Afghanistan", 32, 13),
  4 => array("Albania", 32, 12)
);

// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]
Saturday, June 5, 2021
 
daniel__
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :