I have a JSON file like this
[
{
"item_id": "342",
"item_title": "James"
},
{
"item_id": "374",
"item_title": "Fred"
}
]
And I would like to get the item_title in PHP but using the item_id.
How would I go about this?
I have
$item_id = 374;
$url = 'file.json';
$data = file_get_contents($url);
$items = json_decode($data);
Thank you.
You can use array_search() and array_column() if you know that key will always exist
echo $items[array_search($item_id,array_column($items,'item_id'))]['item_title'];
https://3v4l.org/Qddcj
Otherwise go for functional approach
$items = json_decode($data,true);
function getItemTitle($array,$item_id){
$key = array_search($item_id,array_column($array,'item_id'));
if($key !==false && isset($array[$key]['item_title'])){
return $array[$key]['item_title'];
}else{
return "no title found for given id ".$item_id;
}
}
echo getItemTitle($items,$item_id);
Output:- https://3v4l.org/ikKWY
In case if same id can be repeated multiple time
$items = json_decode($json,true);
foreach($items as $value){
if($value['item_id']==$item_id){
echo $value['item_title'].PHP_EOL;
}
}
Output:- https://3v4l.org/7oPHk
Some explanation: you should use foreach loop with if condition
Here is the sample code
<?php
$json='[
{
"item_id": "342",
"item_title": "James"
},
{
"item_id": "374",
"item_title": "Fred"
}
]';
$item_id = 374;
$items = json_decode($json);
//print_r($items);
foreach($items as $value){
if($value->item_id==$item_id){
echo $value->item_title;
}
}
You can check the desired output here
Related
$json='{
"status": true,
"data": {
"code": "44882S",
"quantity": 124740,
"amount": 124740,
"date": "2020-01-15"
}
}';
and I've made the code and the code doesn't work
$get = json_decode($json, true);
foreach ($get->data as $key) {
$code = $key->code;
$quantity = $key->quantity;
$amount = $key->amount;
$date = $key->date;
}
Is there something wrong with my code?
You requested json_decode to make the objects into arrays!
So either dont ask for the objects to be converted to an array
Also if you are looping over the object/array, you will get One entery per iteration and not all 4 at once.
$get = json_decode($json);
foreach ($get->data as $key=>$val) {
echo "$key = $val";
}
OR treat each value as an array value
$get = json_decode($json, true);
foreach ($get['data'] as $key=>$val) {
echo "$key = $val";
}
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);
`{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}`
I am trying to get the value of rno using PHP code
`$data = json_decode($json, true);
foreach ($data as $item) {
$name = $item['name'] ;
$number= $item['rno'] ;
}`
#Sahil Gulati's code is more prefect and right way to parse the json in php
here is an other way to parse the json data in php
<?php
$data = json_decode($json, true);
foreach ($data as $item) {
foreach ($item as $val) {
echo $name = $val['name'];
echo $number = $val['rno'];
}
}
?>
the above code that i have shared you can understand easily. but after learning that how to parse json data in php you should use #Sahil Gulati's mathod.
Change this to:
foreach ($data as $item)
This:
foreach ($data["student"] as $item)
Try code snippet here
PHP code:
<?php
ini_set('display_errors', 1);
$data = json_decode($json, true);
foreach ($data["student"] as $item)
{
$name = $item['name'];
$number = $item['rno'];
}
You should take a closer look at the structure of the json encoded data. That helps to implement a clean iteration:
<?php
$input = <<<JSON
{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}
JSON;
$data = json_decode($input);
$output = [];
array_walk($data->student, function($entry) use (&$output) {
$output[] = $entry->rno;
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => 187654
)
The output format has been chosen as an array, since the json structure suggests that multiple students can be contained.
If you are only directly interested in the rno property of the first entry in the student array, then you can access it directly:
<?php
$input = <<<JSON
{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}
JSON;
$data = json_decode($input);
var_dump($data->student[0]->rno);
The output of that variant obviously is:
string(6) "187654"
I would like to read the following JSON info in PHP using a foreach. Im new to this and need some help. I have only included a small sample of the data for privacy reasons.
The end goal is to get all the "id" and the "real_address" in the server array.
[
{
"id":"d87df8g7sdfg89",
"status":false,
"servers":[
{
"status":false,
"platform":null,
"server_id":"adsfasdfasdfasdf",
"virt_address6":"fd00:c0a8:f800:0:192:168:248:5",
"virt_address":"192.168.248.5",
"name":"Private",
"real_address":null,
"connected_since":null,
"id":"aasdfasdfasdfsafde",
"device_name":null
}
],
},
{
"id":"asd89asd8f",
"status":true,
"servers":[
{
"status":true,
"platform":"linux",
"server_id":"fasdsdfasdfasdf",
"virt_address6":"fd00:c0a8:f800:0:192:168:248:3",
"virt_address":"192.168.248.3",
"name":"Private",
"real_address":"5.5.5.52",
"connected_since":1447406908,
"id":"asdfasdfasdfasdf",
"device_name":"thriving-fields-2667"
}
],
}
]
You can use json_decode
$data = json_decode($json, true);
foreach ($data as $value) {
foreach ($value['servers'] as $server) {
echo $server['real_address'];
}
}
something like this ...
$items = json_decode($json);
foreach($items as $item){
foreach($item->servers as $server)
{
echo $server->server_id . " - ". $server->status;
}
}
If you have PHP >= 5.5.0 for array_column() you can try this:
$array = json_decode($json, true);
foreach (array_column($array, 'servers') as $server) {
echo $server['real_address'];
}