I am trying to get access to some data in PHP. If I print my docuements as a JSON object I get the document like so:
print_r($url);
[
{
"channel": "hello.com",
"partone": {
"click": 30580,
"load": 2156552
},
"parttwo": {
"click": 3274,
"load": 402327
},
"partthree": {
"click": 406467,
"load": 903869
}
}
]
So my main idea is to get the "click" of "parttwo" but I am getting null. This is my PHP code where I am making the mistake:
foreach ($url[0]['parttwo'] as $obj) {
$doc = array();
$doc['click'] = $obj['click'];
$param []= $doc;
}
Fo that data, simply:
$array = json_decode($url, true);
$param = $array[0]['part2']['click'];
If you really need to loop then:
foreach($array as $value) {
$param[] = $value['part2']['click'];
}
Related
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.
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
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);
i'm having some troubles creating a multidimentional JSON object in PHP.
My Postgresql database looks like this:
Id Name Parent
1 Active NULL
2 Passive NULL
3 Fixed 1
4 Dynamic 3
5 Taxes 2
6 Fair 2
...
The parent column is linked with the Id in the first column
What i want to accomplish is this:
[
{
"name": "Active",
"children": [
{
"name": "Fixed",
"children": [
{
"name": "Dynamic",
"children": NULL
}
]
}
]
},
{
"name": "Passive",
"children": [
{
"name": "Taxes",
"children": NULL
},
{
"name": "Fair",
"children": NULL
}
]
}
]
So first of all i FETCH the data out of our database with
$result = fetchAll(PDO::FETCH_OBJ); // fetches every row in an object
i could send this result to the frontend (javascript) and convert this data to JSON there but then i send the column names with it and i don't think that is a good idea in security terms.
First of all i want to make the top level of the JSON file. With the help of this topic Object to array in PHP i manage to put that together:
$mainArray = [];
foreach ($result as $value) {
if ($value['Parent'] === NULL) {
$object = new stdClass();
$object->name = $value['Name'];
$object->children = [];
$mainArray[] = $object;
}
}
This is my result:
[
{
name: "Actief",
children: [ ]
},
{
name: "Passief",
children: [ ]
}
]
But i'm stuck adding children to the correct parent. I just can't seem to find how to do it.
I need to do something like this:
Add Fixed to Object where Object->Name is 1 = Active.
This will do the job. Assuming your child data won't come before your parent data.
$mainArray = [];
foreach ($result as $key=>$value) {
if ($value['Parent'] === NULL) {
$object = new stdClass();
$object->name = $value['Name'];
$mainArray[$value['Id']] = $object;
}else{
$childOBJ = new stdClass();
$childOBJ->name = $value['Name'];
$mainArray[$value['Parent']]->children[] = $childOBJ;
}
}
$finalArray = array_values($mainArray); // changes to indexed array for json purpose
UPDATE: WITH RECURSION and refrence
function makeTree($result, $parentId=NULL){
$tree = [];
foreach ($result as $value) {
if($value['Parent'] == $parentId){
$object = new stdClass();
$object->name = $value['Name'];
$child = makeTree($result, $value['Id']);
if($child){
$object->children=$child;
}
$tree[] = $object;
}
}
return $tree;
}
$finalArray = makeTree($result);
I was trying to parsing json file below from a link but I still can't figure it out about parsing and display it with foreach.
data: [
{
id: "1072",
nik: "013977",
status: "",
name: "RAKHMAT KUSNADI",
birthdate: "1983-10-21",
email: "rakhmat.koes#gmail.com",
first_login: "0",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1102",
employee_id: "1072",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
{
id: "1069",
nik: "013377",
status: "",
name: "RENATA MARINGKA",
birthdate: "1987-05-20",
email: "",
first_login: "1",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1099",
employee_id: "1069",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
]
}
I want to display name and profile_pics where department id is 101.
Does anybody know how to parse it with foreach?
Reinventing the wheel, are we? Why not simply use:
$jsonObj = json_decode($jsonString);//returns stdClass instance, just an object
$jsonArr = json_decode($jsonString, true);//converts object to associative array
Read more on json_decode here... It's quite easy to use, really
If you decode the data to an array, you could loop through the data like so
while($item = array_shift($jsonArr))
{
foreach ($item as $key => $value)
{
echo $key.' => '.$value."\n";
}
}
Or simply use any old for/foreach loop on an object, its a traversable object anyway (though it doesn't implement the Traversable interface)
First step is to convert to an array
$data = json_decode($json);
Once you've got the array, you can then loop through it and check the values
$keepers = array();
foreach ($data as $item) {
if ($item->placement->department_id == 101) {
$keepers[] = $item;
}
}
Use json_decode
$arr = json_decode($jsonstring, true);
then use foreach loop
foreach($arr as $val) {
if($val['placement']['department_id'] == "101") {
//display what u want
}
}
Probably something like:
$data = json_decode($your_json);
foreach($data as $object) {
echo 'This is the name: ' . $object->name . PHP_EOL ;
}
$data = json_decode($json, true)
Then whatever info you want out you get out with the foreach loop
foreach ($data->id as $id)
{
echo $id;
}
With that you can set any variable like $data->nik as $nik or whatever you want then echo them back
usr this
foreach ($data->id as $id)
{
echo $id;
}