I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?
Related
I have this text from file_get_contents('php://input'):
[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]
I need to get single element like email or event, but haven't been able to get json_decode and others to work.
$obj = json_decode(file_get_contents('php://input'));
How can I reference a single element in the json data?
You have an array, so, you need to get the first element:
$json = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($json);
echo $obj[0]->email; //output text#examlple.com
Here you go, here's a fully working answer:
<?php
$str = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($str);
echo $obj[0]->email;
Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode
I'm new to PHP and web programming at all.I am trying to read some json data from steam API.
Data: http://pastebin.com/hVWyLrfZ
I managed to get to single objects(I believe?).
This is my code:
<?php
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$heroes = reset(reset($data));
//var_dump($heroes);
$wat = reset($heroes);
$antimage = array_values($heroes)[0];
var_dump($antimage);
?>
I want data to be in array like this:
id => name
I mean, array keys should be ids and values should be hero names.
Also,the where I set heroes variable to reset(reset($data)) seems like a bad way of doing what I want, maybe there are better ways?
You can use array_map() function to extract both id and names in two separate arrays and then use array_combine() to create a key-value pair array from the previously extracted arrays.
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON, true);
$ids = array_map(function($a) {
return $a['id'];
}, $data['result']['heroes']);
$names = array_map(function($a) {
return $a['name'];
}, $data['result']['heroes']);
$heroes = array_combine($ids, $names);
print_r($heroes);
A simpler more obvious solution is to simply loop thru it. From your pastebin, I see that your data is wrapped in two levels of array so ...
$myResult = [];
foreach ($data['result']['heroes'] as $nameId) {
$myResult[$nameId['id']] = $nameId['name'];
}
(No need to do any reset calls; that's a weird way to get the first element of an array)
Note, for this to work, you must apply the tip by #RamRaider
$data = json_decode($JSON, true);
in order for json_decode to return arrays, not StdClass.
I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);
I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as
$json = '{"value":"somevalue"}';
Using this:
<?php
$json = '{"value":"somevalue"}';
$obj = json_decode(json_encode($json));
print $obj->{'value'};
?>
But when i try an get a value from the following json string it throws an error...
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
I validated the json on JSONlint but not sure how to access the values within this with php.
Thanks
You can try this:
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
//since $json is a valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
You can pass true as a second parameter to json_decode() to get the results as an array
$my_arr = json_decode($json, true);
var_dump($my_arr);
Should help you. You can then step through the array as you would normally.
use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for