how to retrieve multiple array json with php - php

i know it sounds so easy. just use foreach looping or json_decode, and you can retrieve json data.
yeah it was, until i got multiple array json when trying retrieving data from elasticsearch.
im confused how to retrieve this :
{
"took":3,
"status": "taken",
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total":2,
"msg":"ilusm",
"hits":
[
{
//goes here
"id":1234
},
{
//goes here
"id":4321
}
]
},
"date-created": "2016-06-06"
}
i use this to retrieve my first data :
$result = json_decode(json_encode($product),true);
echo "total took:";
echo $result['took'];
echo "total shards:";
echo $result['_shards']['total'];
the problem is,i cant retrieve data inside hits.
how can i retrieve hits id : 1234 ?
echo"view all total hits :";
echo $result['hits']['total'];
echo"view all total msg:";
echo $result['hits']['msg'];
echo"view hist data :";
echo json_decode(json_encode($result['hits']['hits']), true);
i got this error :
Message: Array to string conversion
please help me to fix this out.
many thanks in advance.

Try this it's work for me.
$result= '{"took":3,"status": "taken","_shards": {"total": 5,"successful": 5,"failed": 0},"hits": {"total":2,"msg":"ilusm","hits":[{"id":1234},{"id":4321}]},"date-created": "2016-06-06"}';
$array= json_decode($result, true);
echo $array["hits"]["hits"][0]['id']; //output 1234
output : 1234

$string = '{"took":3,"status": "taken","_shards": {"total": 5,"successful": 5,"failed": 0},"hits": {"total":2,"msg":"ilusm","hits":[{"id":1234},{"id":4321}]},"date-created": "2016-06-06"}';
$hits= json_decode($string, true);
$hits = $hits['hits']['hits'];
foreach($hits as $hitsIndex => $hitsValue){
if($hitsValue["id"] == '1234'){
var_dump($hitsValue["id"]);
}
}

I think you are a little confused about json & php data management.
Should you tell us what $product variable is? (string,object/array).
Usually you get json data as string and parse it to php variables with json_decode.
Your Javascript-like object declaration of $product is useless.

Related

Get JSON Data From .json (php)

i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D
{
"status": 300,
"data": {
"date": "2019-09-16T00:00:00.000Z",
"featured": [
{
"name": "Flying Saucer",
"price": "1,200",
"images": {
"icon": icon.png",
},
"rarity": "epic",
},
I'm using this that a friend told me, but i cant put that to work :c
<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {
$item = $val['name'];
echo "<b>$item</b>";
}
?>
I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:
echo $response['status']; // would output 300
You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:
foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
echo $val['featured']['name'];
}
You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.
When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.
I suggest you to read about json_decode and json in general:
JSON: https://www.json.org/
json_decode function: https://www.php.net/manual/en/function.json-decode.php

How to correctly parse JSON in PHP

I want to parse values from an Json API, but I cant get it to work
The API returns this JSON:
[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]
I tried to get the ID value like this:
$json_obj = json_decode($resp);
print $json_obj->assets[0]->id;
but I get no result whereas it should be 6. What do I do wrong here?
Remember the outer part of the JSON is an array, as suggested by the opening [. So you need to first access the first (and only) element of it:
$json_obj[0]->assets[0]->id; //<-- note the first [0]
I think the correct answer is
$json_obj = json_decode($resp);
print $json_obj[0]->assets[0]->id;
The json object will be converted to a php array, since you have an array with a object inside in your case it will be a multidimentional array with the objects inside.
Try this its worked for me..
$json ='[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]';
$json_obj = json_decode($json);
var_dump($json_obj[0]->assets[0]->id)
?>
decode JSON to the array and fetch the id by proper array keys
$jToArray = json_decode($resp, TRUE);
echo $jToArray[0]['assets'][0]['id'];//You will get the correct id

echo results from an google safe browsing api array

I know this is a basic question, but I cannot figure out how to actually do this. I have read countless tutorials about it but they seemingly do not work.
var_dump($google_check);
returns the following:
string(488) "{
"matches": [
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
},
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
}
]
}
"
I want to echo results from the array, so something like
echo $google_check[0][matches][threat];
echo $google_check[1][matches][threat];
Problem is this returns illegal offset on matches and threat, and only echo's a single character {
What am I doing wrong? How do I echo the results from this array without dumping the entire array?
The response you recieved is in json so you'll need to first json_decode the response.
$decoded = json_decode($google_check, true);
Then you can access it like an array
echo $decoded['matches'][0]['threat'];
echo $decoded['matches'][1]['threat'];
if you want the url value you'll need to do it like this.
echo $decoded['matches'][0]['threat']['url'];
echo $decoded['matches'][1]['threat']['url'];
please also note, when looking at array keys that aren't numerical you'll need to wrap in quotes (e.g. $decoded['matches'] instead of $decoded[matches]).
Here's a quick explanation on json
https://www.tutorialspoint.com/json/json_php_example.htm

Parsing Multidimensional Nested JSON with PHP

I feel like i am slightly insane, and I have certainly read the docs on this. I am completely unable to echo out various objects in a JSON array in PHP. I am not sure what I'm doing wrong, but I'm ripping my hair out...
Here is my JSON array:
{
"photos": {
"page": 1,
"pages": 1569045,
"perpage": 1,
"total": "1569045",
"photo": [
{
"id": "14842817422",
"owner": "23432140#N06",
"secret": "c37cfa1914",
"server": "3864",
"farm": 4,
"title": "pizza",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}
]
},
"stat": "ok"
}
I know this is simple, but I can't get it right. I would like to echo out four different values.
This is what I have been trying:
$photoId = $jsonDecoded['photos']['photo'][0]['id'];
$photoSecret = $jsonDecoded['photos']['photo'][0]['secret'];
$photoServer = $jsonDecoded['photos']['photo'][0]['server'];
$photoFarm = $jsonDecoded['photos']['photo'][0]['farm'];
I know this seems newbie. Please help...
Best,
The problem is that you have both objects and arrays in your json, but are using array syntax in your php.
There are two ways to fix this, 1st simply set the second parameter of json_decode to true:
json_decode($json, true);
This will create a multidimentional array you can access as suggested in your question, eg:
$photoId = $jsonDecoded['photos']['photo'][0]['id'];
Alertinitivly you can use object property syntax on your existing $jsonDecoded:
$photoId = $jsonDecoded->photos->photo[0]->id;
if there are multiple photo sub arrays then you can do like this.
//this will create array instead of object
$jsonDecoded = json_decode($your_feed_data,true);
foreach($jsonDecoded['photos']['photo'] as $sub_array){
$photoId = $sub_array['id'];
$photoSecret = $sub_array['secret'];
$photoServer = $sub_array['server'];
$photoFarm = $sub_array['farm'];
}

json_encode, json_decode, array?

I'm trying to get into just data from
{
"data": [{
"media_count": 3045,
"name": "snow",
},
{
"media_count": 79,
"name": "snowman",
},
{
"media_count": 40,
"name": "snowday",
},
{
"media_count": 29,
"name": "snowy",
}]
}
I've been trying, using:
$obj = json_decode($res[0], true);
echo $obj['data']; //this returns an array
I also tried this:
$obj = json_encode($res[0], true);
echo $obj; // this returns json, but not inside `data`
"data": [{
"media_count":54373,
"name":"test"
}]
I just want to get inside data. How would I do so?
Thanks in advance!
UPDATE: Sorry to mention, I would like this in json format please
eventually, I would like to only see
{
"media_count":54373,
"name":"test"
}
Something like thiat
Use json_encode() to get what you want:
$obj = json_decode($res[0], true);
echo json_encode($obj['data']);
In your first example, $obj['data'] returns an array because that's how the JSON is set up. According to the JSON, data is a collection of elements.
To access within the array, you can do this:
foreach($obj['data'] as $object) {
print_r($object);
}
You can also index into it as you want:
print_r($obj['data'][0]);
EDIT
If I'm getting you correct, you want to convert the first JSON to this:
"data": [{
"media_count":54373,
"name":"test"
}]
If so, that is not possible since the second fragment is not valid JSON. (use http://jsonlint.com)
firstly access the data item of the json array;
$obj1=$obj[item];
$sizeobj=sizeof($obj1);
for($i=0;$i<$sizeobj;$i++)
{
// your code to access the data items
// for eg $obj[item][$i][media_count}
}

Categories