Filter response from json with php - php

for example, i have json result like this
[
{
"title": "x1",
"url": "domain.com"
},
{
"title": "x2",
"url": "example.com/"
},
{
"title": "x3",
"url": "site.com/cam"
},
]
The result of json will be randomly, i want to scrape ['x']['url'] path from that json, but the value of ['url'] must be "site.com/cam", and as you know, the results from json will change randomly, so I do not know which json path with value is "site.com/cam".
is there any suggestion? Thank you

Try this
$index = array_search('site.com/cam',array_column(json_decode($json),'url'));
Sandbox
https://3v4l.org/72tsZ
Output
$index = 2
Oh and there is a typo in your JSON
}, <-- remove comma here.
]

Related

JSON Parsing Error: Warning: Attempt to read property on array

am trying to parse this JSON from a Football API using PHP.
Below is a subset of the JSON output.
Specifically, I am trying to retrieve the “45%” value from the "home" element from the below json.
$json = '{
"get": "predictions",
"parameters": {
"fixture": "198772"
},
"errors": [],
"results": 1,
"paging": {
"current": 1,
"total": 1
},
"response": [{
"predictions": {
"winner": {
"id": 1189,
"name": "Deportivo Santani",
"comment": "Win or draw"
},
"win_or_draw": true,
"under_over": "-3.5",
"goals": {
"home": "-2.5",
"away": "-1.5"
},
"advice": "Combo Double chance : Deportivo Santani or draw and -3.5 goals",
"percent": {
"home": "45%",
"draw": "45%",
"away": "10%"
}
}
}]
}';
I have tried the following codes but it does not work
$response = json_decode($json);
echo 'Output: '. $response->response->predictions->percent->home;
The error i am getting is:
Warning: Attempt to read property "predictions" on array in C:\xampp\htdocs\xampp\livescore\api-test\predictions.php on line 93
I also tried this but no luck.
echo 'Output: '. $response->response[0]->predictions[0]->percent[0]->home;
appreciate any help or insights I can get.
thanks in advance.
Whenever you see a [ in a json (or any other) object, it's the start of an array, and to reach a child of that array you have to reference it's index (postition). For what you want, this would do it.
$response = json_decode($json);
echo 'Output: '. $response->response[0]->predictions->percent->home;
"response": [{ shows the beginning of an array, and since there's only one item in the array (starting with {) you can reference it by it's index 0. If there were many items in the array, you could loop over them, like
$response->response.forEach(arrayItem => {
// arrayItem is the current element in the array you're looping though
})
You've probably missed that only value of "response" is an array, which has dictionary inside.
Try this: $response->response[0]->predictions->percent->home

How to parse JSON from Url and named array

I'm trying to parse a JSON string from a url with a named array.
Ex.
{
"Attendees": [{
"user_id": "123",
"first_name": "Jim",
"last_name": "Bill",
"email": "jsfbsjkd#aim.com",
"title": "Admin",
"business_unit": "",
"area": ""
}]
}
i've tired this:
$(document).ready(function(){
$.getJSON('http://localhost/testJSON/json.php', function(data){
alert(data.user_id); // 1 });
});
but it's creating Object Object. Any help is appreciated.
Instead of alert(), try this:
console.log(data.Attendees[0].user_id);
Then using developer tools in Chrome (or another developer friendly browser), check the console for the result here.

How to extract the JSON encoded POST parameters in PHP

I have passed JSON encoded parameters by POST which we have captured and decoded in another PHP file. I have used the following code to do that.
$entityBody = file_get_contents('php://input');
$entityBody = json_decode($entityBody, true);
I have passed the JSON encoded parameters as follows:
{
"id": "5",
"name": "abcd",
"imei": "1234"
}
Here my code works perfectly fine. However, I want to get all the parameters into a single object so that we can store them efficiently because otherwise there will be too many ifs and elses to get each parameter. So I have encoded the parameters as follows:
device = {
"id": "5",
"name": "abcd",
"imei": "1234"
}
But it is not working. Being new to JSON and PHP I do not know how to handle such cases. How can I achieve this?
use json_decode($_POST['device'], true) since your actually passing a parameter called 'device' to the php file.
You should pass json objects as follow:
{"device" : {
"id": "5",
"name": "abcd",
"imei": "1234"
}}
or if you have an array of devices
{"device" : [{
"id": "5",
"name": "abcd",
"imei": "1234"}
]}

php json_encode issue in utf-8

I have following array in php
$array = array(
array('name'=>'abc', 'text'=>'اسلسصثصض صثصهخه عه☆anton & budi☆' ),
array('name'=>'xyz', 'text'=>'nice' ),
);
when i use json_encode, the result is different :
[
{
"name": "abc",
"text": "\u0627\u0633\u0644\u0633\u0635\u062b\u0635\u0636 \u0635\u062b\u0635\u0647\u062e\u0647 \u0639\u0647\u2606anton '<&>' budi\u2606"
},
{
"name": "xyz",
"text": "nice"
}
]
why the result is not like this ?
[
{
"name": "abc",
"text": "اسلسصثصض صثصهخه عه☆anton & budi☆"
},
{
"name": "xyz",
"text": "nice"
}
]
Thanks
Because PHP doesn't assume/allow a non-ASCII character set when encoding. Both results are equivalent when decoded.
Because it is encoded to JSON. With your first output, you are absolutely 100% certain that the browser will receive what you want it to. With the second, you cannot be sure.
Try this:
//for encode
json_encode(array_map('base64_encode', $array));
//and for decode
array_map('base64_decode', json_decode($array));
Hope it helps

Accessing data from a json structure

I am loading in a JSON feed from Facebook (snippet below).
{
"data": [
{
"id": "115972604762",
"from": {
"name": "Title Here",
"category": "Musicians",
"id": "20274769762"
},
"name": "It was an amazing gig!!",
"picture": "http://photos-h.ak.fbcdn.net/hphotos-ak-snc1/hs196.snc1/6616_115972604762_20274769762_2185148_6347071_s.jpg",
"source": "http://sphotos.ak.fbcdn.net/hphotos-ak-snc1/hs196.snc1/6616_115972604762_20274769762_2185148_6347071_n.jpg",
"height": 453,
"width": 604,
"images": [
{
I am loading it in using $data['pics'] = json_decode(file_get_contents('https://graph.facebook.com/'. $id .'/photos'));
How would I go about echo'ing out the from->name value to get the 'Title Here' value?
I think it should just be this:
$array = json_decode(file_get_contents('https://graph.facebook.com/'. $id .'/photos'));
echo $array["data"]["from"]["name"];
You can echo out the array using print_r($array) and then see the structure of your php array if it didn't work as expected.
First thing I would do is var_dump() the response, that would explain the exact structure of how PHP has decoded it. My guess is that $response['data']['from']['name'] might work.

Categories