Chidiebere Ezeka
Chidiebere Ezeka

Reputation: 33

How to access this array containing objects in Laravel

The table filed name is called metadata, and within the metadata contained an array of objects such as

[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]

How do I access it using PHP/Laravel. Any help is appreciated. Thanks

Upvotes: 1

Views: 66

Answers (2)

Robin Gillitzer
Robin Gillitzer

Reputation: 1602

The code you have posted is a JSON string. So you first have to decode it to a PHP array with the function json_decode. After that you can access it easily.

Try this out:

$json = '[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]';
$assoc_array = json_decode($json, true); // second parameter is true to get an associative array
echo $assoc_array[0]['title'];

Upvotes: 0

STA
STA

Reputation: 34678

You need to decode it, with json_decode() php function :

$x = '[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]';
$y = json_decode($x, true);
print_r($y);

Output :

Array
(
 [0] => Array
     (
         [title] => Type
         [value] => Hard Drive (HDD)
     )

 [1] => Array
     (
         [title] => Condition
         [value] => Used
     )
)

Now you can access the value with foreach loop as :

foreach($y as $key => $val) {
      echo "Title : " . $val['title'] . $val['value'] ;
 }

Above code tested here

Upvotes: 1

Related Questions