How to access this array containing objects in Laravel - php

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

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

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

Related

get array value from std object in php

I have an array like below. I want to extract the values . Help me out please. But this doesn't print anything. Please help me.Any help would be appreciated.May you all find this question similar.But I am unable to find any answer,because that's the way we do to find the array values.
Array
(
[0] => stdClass Object
(
[bHeader] => stdClass Object
(
[ei] => NSE
[seg] => I
)
[cNetChangeIndicator] =>
[fClosingIndex] => 10558.5
[fHighIndexValue] => 10532
[fIndexValue] => 10469
[fLowIndexValue] => 10438.5
[fOpeningIndex] => 10499.5
[fPercentChange] => -0.85
[sIndexName] => 962450
[fChange] => -89.5
[iIdxId] => 311
)
)
Thanks in advance
convert your object in to array using
$array = (array) $yourObject;
if you use json_decode than give second parameter true e.g
$array = json_decode($jsonStr,TRUE);
It will return array so no need to typecast(conveting) obj to array
also used operator '->' which help to fetch data from object
You are accessing the object in the array as if it is also an array.
You need to access the object's properties using ->
echo $arr[0]->fIndexValue;
echo $arr[0]->fChange;
echo $arr[0]->fPercentChange';
For example:
$obj = new stdClass;
$obj->fIndexValue = 10469;
$arr = array();
$arr[0] = $obj;
echo $arr[0]->fIndexValue;
Prints "10469".
Try this to print the whole thing, assuming your var is $arr:
print_r($arr);
Or for variables
print($arr[0]-->fIndexValue);

Search array of object from JSON data with PHP for a match and then update the matching keys data

I am trying to read a file of JSON data into PHP and search its array or objects for a matching anme value. If a match is found I want to update the content of that array objects data from a form POST data to update the item and then convert back to JSON and save to the json file.
$file = 'plugins.js';
$tmp_json_data = file_get_contents($file);
$data = json_decode($tmp_json_data);
echo '<pre>';
print_r($data);
foreach ($data as $key => $obj) {
echo $obj->name;
echo $obj->url;
echo $obj->tag;
}
Result
Array
(
[0] => stdClass Object
(
[name] => Roundabout - Interactive, turntable-like areas
[url] => http://fredhq.com/projects/roundabout/
[tag] => slide
)
[1] => stdClass Object
(
[name] => Slides - Simple slideshow plugin for jQuery
[url] => http://slidesjs.com/
[tag] => slide
)
)
How can I read my $data array in PHP and search for a matching object name that is equal to $_POST['name'] and if a match is found, update the content of that array object?
I would use an array (an object will work in PHP 7):
$data = json_decode($tmp_json_data, true);
$key = array_search($_POST['name'], array_column($data, 'name'));
Then, I'm not sure what you mean by update, but:
$data[$key]['url'] = 'something new';

PHP how to properly loop through json with multiple levels as object

Here is the Json data stored in variable $json
[Data] => Array
(
[id_number] => Array
(
[value] => 123445567
[link] => 1234556
[class] =>
)
[date] => Array
(
[value] => 04-18-14
[link] => 1234556
[class] =>
)
Currently I access the lower levels like this:
foreach($json['Data'] as $data) {
foreach ($data['id_number'] as $id) {
print $id['value'];
}
}
There is only one result for id_number and only one result for date. Do I really need this second foreach loop? Isn't there a way to access it by just going to the lower level as an object so it would be something like
print $data->id_number->value
Thank you.
Since you have decoded the JSON string as an array you could do
foreach($json['Data'] as $data) {
print $data['id_number']['value'];
}
If you had decoded it into an object (don't set the second parameter to be true) then you could simply do it like you mentioned
foreach($json->Data as $data)
print $data->id_number->value;
Manual
You can retrieve the elements individually (without looping) by:
$id_number = $json['Data']['id_number']['value'];
$date = $json['Data']['date']['value'];
//etc ...
You can use:
$json['Data'][idnr]->value
If you know the id that is ofc, else you will have to loop

Accessing JSON array after json_decode/multidimensional array

I'm pulling in a search from the Twitter api, fetching the data with file_get_contents and then passing to json_decode which give me this array structure.
{"results":[
{
"from_user":"A-user-name",
"from_user_id":457304735,
"text":"Ich R U #BoysNoize #SuperRola",
"entities":{
"urls":[{
"url":"http:\/\/t.co\/WZnUf68j",
"expanded_url":"http:\/\/instagr.am\/p\/Vz4Nnbnjd6\/",
}]
}]
]
This repeats for every tweet pulled, Now I can access the user name and text using a foreach loop and assigning every instance of results to a variable, then pulling data from the variable.
foreach($jsonArr['results'] as $item){
// Takes the Array jsonArr and for every results heading creates an $item
$user = mysql_real_escape_string($item['from_user']);
$text = mysql_real_escape_string($item['text']);
This saves the correct variables OK, But I can't seem to get the the data within the entities array within the results. If I print out the Entities var like the username or text I get
ArrayArrayArrayArrayArrayArrayArrayArrayArrayArray
So It holds the arrays for each results returned but how on earth do I access it, I've been messing around with a few other methods I know for accessing array data but they all seem to fall flat. Any help with how to get at these values, or integrate them with the foreach would be greatly appreciated
Assuming that you've chosen to decode the JSON as a multi-dimensional array, rather than as objects:
foreach ($results as $tweet) {
$user = $tweet["from-user"];
$text = $tweet["text"];
$entities = $tweet["enities"];
$urls = $entities["urls"];
foreach ($urls as $url) {
echo $url["expanded_url"];
}
}
et cetera
Array
(
[results] => Array
(
[0] => stdClass Object
(
[entities] => Array
(
[0] => stdClass Object
(
[urls] => Array
(
[0] => stdClass Object
(
[expanded_url] => http://instagr.am/p/Vz4Nnbnjd6/
[url] => http://t.co/WZnUf68j
)
)
)
)
[from_user] => A-user-name
[from_user_id] => 457304735
[text] => Ich R U #BoysNoize #SuperRola
)
)
)
Accessing url:
$json_array['results'][0]->entities[0]->urls[0]->url;
Helpful code:
<?php
$json ='{ "results" : [ { "entities" :
[ { "urls" : [ { "expanded_url" : "http://instagr.am/p/Vz4Nnbnjd6/",
"url" : "http://t.co/WZnUf68j"
} ] } ],
"from_user" : "A-user-name",
"from_user_id" : 457304735,
"text" : "Ich R U #BoysNoize #SuperRola"
} ] }';
$json_array = (array)(json_decode($json));
echo '<pre>';
//print_r($json_array);
echo $json_array['results'][0]->entities[0]->urls[0]->url;
?>
Just do a print_r($jsonArr); and you will be able to work with your decoded json.

PHP rewriting a json array (Undefined offset)

I'm taking some json, made by OpenLibrary.org, and remake a new array from the info.
Link to the OpenLibrary json
here is my PHP code to decode the json:
$barcode = "9781599953540";
function parseInfo($barcode) {
$url = "http://openlibrary.org/api/books?bibkeys=ISBN:" . $barcode . "&jscmd=data&format=json";
$contents = file_get_contents($url);
$json = json_decode($contents, true);
return $json;
}
the new array I'm trying to make looks something like this:
$newJsonArray = array($barcode, $isbn13, $isbn10, $openLibrary, $title, $subTitle, $publishData, $pagination, $author0, $author1, $author2, $author3, $imageLarge, $imageMedium, $imageSmall);
but when I try to get the ISBN_13 to save it to $isbn13, I get an error:
Notice: Undefined offset: 0 in ... on line 38
// Line 38
$isbn13 = $array[0]['identifiers']['isbn_13'];
And even if I try $array[1] ,[2], [3].... I get the same thing. What am I doning wrong here! O I know my Valuable names might not be the same, that's because they are in different functions.
Thanks for your help.
Your array is not indexed by integers, it is indexed by ISBN numbers:
Array
(
// This is the first level of array key!
[ISBN:9781599953540] => Array
(
[publishers] => Array
(
[0] => Array
(
[name] => Center Street
)
)
[pagination] => 376 p.
[subtitle] => the books of mortals
[title] => Forbidden
[url] => http://openlibrary.org/books/OL24997280M/Forbidden
[identifiers] => Array
(
[isbn_13] => Array
(
[0] => 9781599953540
)
[openlibrary] => Array
(
[0] => OL24997280M
)
So, you need to call it by the first ISBN, and the key isbn_13 is itself an array which you must access by element:
// Gets the first isbn_13 for this item:
$isbn13 = $array['ISBN:9781599953540']['identifiers']['isbn_13'][0];
Or if you need a loop over many of them:
foreach ($array as $isbn => $values) {
$current_isbn13 = $values['identifiers']['isbn_13'][0];
}
If you expect only one each time and must be able to get its key without knowing it ahead of time but don't want a loop, you can use array_keys():
// Get all ISBN keys:
$isbn_keys = array_keys($array);
// Pull the first one:
$your_item = $isbn_keys[0];
// And use it as your index to $array
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];
If you have PHP 5.4, you can skip a step via array dereferencing!:
// PHP >= 5.4 only
$your_item = array_keys($array)[0];
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];

Categories