Get values from JSON array in PHP with the following format? - php

I have got this array from the Android developer whom I am working with and I have to get the values of the key name from the following array:
[
{
"data":"[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
"status":1
}
]
I have tried doing the following:
<?php
$s = '[
{
"data": "[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
echo $obj[0]['data']
?>
Which gives me following output:
[
{
"name": "step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd "
},
{
"name": "step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf"
},
{
"name": "step 3 kkkkkkkkkk"
},
{
"name": "step 4 ljlejrhlflhgf dfhjk"
}
]
But I want just the values of the key name like:
step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd
step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf
step 3 kkkkkkkkkk
.
.
.
My question is similar to this one:
Get value from JSON array in PHP
except the format is different.
Can I get the values in this format? If so, how? If not, is the format incorrect?

Assuming $obj[0]['data'] actually has the JSON that you posted, just decode and extract the name columns:
foreach(array_column(json_decode($obj[0]['data'], true), 'name') as $name) {
echo $name;
}

First of all you have not a json-structure inside the "data" field, but just a string, which contains json data.
Therefore you did it wrong, when convert the data into a constant value. You have to double all backslashes first.
Then you can get the "data" element and perform json_decode once more.
<?php
$s = '[
{
"data": "[{\\"name\\":\\"step 1 kdfhghdkgjdf\\\\nkjdhfgkjhdkjghd\\\\nkdfjhgkjdhfg\\\\n\\\\n\\\\ndfjhgkjdfjhgdfgd\\\\n\\"},{\\"name\\":\\"step 2 dhfgkjdfhkhkjchjkfd\\\\ndkjhjdf\\\\njhkdfhkghdkfhgkdhg\\\\n\\\\n\\\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\\"},{\\"name\\":\\"step 3 kkkkkkkkkk\\"},{\\"name\\":\\"step 4 ljlejrhlflhgf\\\\n\\\\n\\\\ndfhjk\\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
$data = json_decode($obj[0]['data'], true);
foreach($data as $item) {
print($item['name'] . "\r\n");
}

Related

PHP array_filtered acces object [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 14 days ago.
I'm trying to filter array from DB and I've got this postman response:
{
"1": {
"id": "3",
"key": "emails_html_body_start",
"value": "value"
}}
How I can access to id, key, value?
My code here:
$start = array_filter($array, function ($var) {
return ($var['key'] == 'emails_html_body_start');
});
echo json_encode($start);
Your question is a bit unclear ... So the upper code is what is sent by the lower code snippet? So the cho json_encode($start); is what produces the upper json data?
If so, then you obviously need to json decode that data again to be able to access a property inside that structure:
<?php
$input = <<<JSON
{
"1": {
"id": "3",
"key": "emails_html_body_start",
"value": "value"
}
}
JSON;
$data = json_decode($input, true);
$output = $data[1]['id'];
print_r($output);
The output obviously is:
3

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

Retrieve data from JSON based on the object index in PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a $abcd variable and the following is the output:
echo $abcd;
//Output:
{
"NID": 2,
"STS": "3",
"Options": {
"Model": "model value",
"Location": "location value",
"Price": "price value",
"Name": "Value"
}
}
In the "Options" I have 3 names and values of each. The names are not fixed and could be anythings and the number of objects in Options could be any from 0 to 100.
I'd like to know if there is any way (JSON format preferred) that I can assign the Names and their related values to two other variables.
$varName[0]=Model
$varValue[0]=model value
$varName[1]=Location
$varValue[1]=location value
$varName[2]=Price
$varValue[2]=price value
i'm not sure what is th logic behind this,
but you may accomplish this by using mix of array_key & array_values like following:
$abcd = '{
"NID": 2,
"STS": "3",
"Options": {
"Model": "model value",
"Location": "location value",
"Price": "price value",
"Name": "Value"
}
}';
$data = json_decode($abcd, true);
$keys = array_keys($data['Options']);
$values = array_values($data['Options']);
echo $keys[0] . " - " . $values[0]; // Model - model value
echo $keys[1] . " - " . $values[1]; // Location - location value
// ..... and so on.
live example: https://3v4l.org/GggRd
$data = json_decode($abcd, true);
foreach($data['Options'] as $index => $value) {
//do whatever you want
}
//or access them directly
$data['Options']['Model']
You dont need to assign them to anything else, just json_decode() the JSONString and they become a PHP Object you can use as is
$obj = json_decode($abcd);
echo $obj->Options->Model;
echo $obj->Options->Location;
echo $obj->Options->Price;
RE your comment#
I said that the names are varies and Model, Location and Price is just an example
then you could do
foreach ($obj->Options as $prop => $val) {
sprintf( '%s = %s', $prop, $val );
}

Multidimensional Array Information Grabbing

I have an array that looks as such:
{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0,
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
},
and from number 1, I need to grab current_price. I have a foreach that grabs it from both, but I'm not sure how to only grab the info from number 1, being the second block of information - TSBC. Any ideas?
As you added the json tag to your question, I must note that you have presented an invalid json content. There is unexpected comma right after the number 0 within the first "stocks" object "available_shares": 0,.
So let's remove that comma and if we talk about "multidimensional array" let's decode our json string into associative array with json_decode function in such way:
// $str - is some part of your json string
$str = '{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
}}}';
$arr = json_decode($str, true);
// now we are able to get 'current_price' from the second element of array
var_dump($arr['stocks'][1]['current_price']);
// the output:
float 503.106

PHP count JSON array

I have searched SO but couldn't find an answer.My PHP script is receiving some JSON by http post that looks like this:
{
"task": [
{
"task_id": "3",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "fff",
"task_time": "20131026_112531",
"task_name": "fff"
},
{
"task_id": "2",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "rff",
"task_time": "20131026_112522",
"task_name": "xff"
},
{
"task_id": "1",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "fggg",
"task_time": "20131026_112516",
"task_name": "ff"
}
]}
As you can see, there are 3 items, but when I turn it into a PHP array object and count the items, I'm returned 1, when it should be 3, here is my PHP code:
$json_tasks = $_POST["json_array"];
$task_array = json_decode($json_tasks,true);
echo count($task_array);
And echo count prints out '1' not '3'.
Try echo count($task_array['task']);
In general, if you wonder what the structure of the value of a variable $var is, do a
<pre><?php var_export($var, true); ?></pre>
Advantage of this function over alternatives such as serialize and print_r is, that it prints PHP code (and is thus readable by anyone who understands PHP (which is likely if you program in PHP)). Disadvantage of var_export is, that it cannot handle circular structures (e.g. if $a->b == $a), but neither can JSON.
Well the 3 items are in 1 item "task" so, you have one array named task and the 3 elements are in it
try
echo count($task_array['task']);
EDIT :
please use the below code to print the array in correct pattern
echo '<pre>';
print_r($task_array['task']);
exit();
$task_array = json_decode($json_tasks);
count($task_array->task);
EX: 3
From Taiwan
try this code, here i can able to count the number of objects with specific value
here's my data.json file content
{"likes":[
{"user_id":1,"time":"12:04pm"},
{"user_id":2,"time":"02:04pm"},
{"user_id":67,"time":"11:04pm"},
{"user_id":1,"time":"12:04pm"}
]}
here's the php code
<?php
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData,true);
$total = 0;
foreach ($data["likes"] as $value) {
if($value["user_id"]==1){
$total = $total+1;
}
}
echo $total;
?>
output will be
2

Categories