how to create json from associate array - php

I am new to PHP. So bear with me. I have to fetch songs from db. I don't know how to initialize associate array in a for loop using keyValuePair. and also add status attribute to it.
What i want is
{
"status" : "true" ,// It tells whether day available or not
"data": [
{
"name": "Joe Bloggs",
"id": "203403465"
},
{
"name": "Fred Bloggs",
"id": "254706567"
},
{
"name": "Barny Rubble",
"id": "453363843"
},
{
"name": "Homer Simpson",
"id": "263508546"
}
]
}
My Code
$html = file_get_html('http://1stfold.com/taskbox/Farrukh/Zare/');
$output = array();// how to initialze it in for loop with keyValue pair
// Find all "A" tags and print their HREFs
foreach($html->find('.branded-page-v2-body a') as $e)
{
if (0 === strpos($e->href, '/watch?v'))
{
$output[] = $e->href . '<br>';
echo $e->href . '<br>';
}
}
echo json_encode($output);
Thanks in Advance.

You can add an array to the $output array, by simply changing this :
$output[] = $e->href . '<br>';
To this :
$output['data'][] = array('name' => $name_value, 'id' => $id_value);
This will push arrays to the the $output['data'] array.
You should add the "status" keyValuePair before the loop

Related

how to update the value of json data label with the new value using php?

I want to update the label value using PHP. Suppose if I enter the same label then it'll match if there exists any same label named, then it'll update the value of that label.
[{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}]
in that above data.json i want to update the value of label : "yy" to val: "20". For this I'm using this code
$myFile = "data.json";
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'label'=> $_POST['label'],
'val' => $_POST['val']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
foreach($arr_data as $item){
}
// array_push($arr_data,$formdata);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
/*this is the matching label code*/
if(in_array($formdata['label'],$item)){
$item['val'] = $formdata['val'];
echo $item['val'];
echo "got it";
}
else echo "not matched";
//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Move the code to match label name inside foreach loop so that each label value in json array can be compared. Updated Code:
$myFile = "data.json";
try {
//Get form data
$formdata = array(
'label' => $_POST['label'],
'val' => $_POST['val']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
foreach ($arr_data as $key => $item) {
/* this is the matching label code */
if ($formdata['label'] == $item["label"]) {
$arr_data[$key]["val"] = $formdata['val'];
echo $item['val'];
echo "got it";
} else
echo "not matched";
}
//write json data into data.json file
if (!file_put_contents($myFile, json_encode($arr_data, JSON_PRETTY_PRINT))) {
echo "error";
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Iterative solution with json_decode() and json_encode()
$jsonData = '[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}
]';
echo '<strong>Before update</strong>';
echo '<pre>';
echo $jsonData;
echo '</pre>';
$jsonArray = json_decode($jsonData, true);
foreach ($jsonArray as $key => $jsonRow) {
if (isset($jsonRow['label']) && $jsonRow['label'] == 'yy') {
$jsonArray[$key]['val'] = 20;
}
}
$jsonData = json_encode($jsonArray, JSON_PRETTY_PRINT);
echo '<strong>After update</strong>';
echo '<pre>';
echo $jsonData;
echo '</pre>';
This code will give output
Before update
[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}
]
After update
[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": 20
}
]
You can use preg_replace.
The pattern of a Json is very predictable.
Using regex means you don't need to decode and encode or even iterate the array.
$label = "yy";
$val = 20;
echo preg_replace("/label\":\s*\"" . $label . "\",\s*\"val\":\s*\"\d+/",
"label\": \"" . $label . "\", \"val\": \"". $val,
$json);
https://3v4l.org/m4rDa
If you need to know if the label has been updated then you can use this:
$label = "yy";
$val = 20;
$new = Preg_replace("/label\":\s*\"" . $label . "\",\s*\"val\":\s*\"\d+/",
"label\": \"" . $label . "\", \"val\": \"". $val,
$json);
If($json != $new){
Echo "label updated\n";
}else{
Echo "nothing found\n";
}
Echo $new;
It will compare the "old" Json with the new and if they don't match the lable has been updated.

How to parse json array using php foreach?

I want to get id,url,img and title of videos in the JSON data.My current code doesn't output anything
could any one tell me what i am doing wrong.Thanks
$code2 = stripslashes($_POST['outputtext']);
$data = json_decode($code2, true);
$i = 0;
foreach($data->videos as $values)
{
echo $values->id . "\n";
echo $values->url . "\n";
echo $values->img . "\n";
echo $values->title . "\n";
$i++;
}
data:
{
"cat": {
"id": "1234567",
"source_id": null,
"title_en": "first season",
"description_en": "This is spring category ",
},
"videos": [{
"id": "312412343",
"url": "\/2015-07-17\/1abcd.mp4",
"img": "image\/44\/\/2015-07-17\/1abcd.jpg",
"title": "first",
}, {
"id": "2342343",
"url": "\/2015-07-16\/2dcdeg.mp4",
"img": "images\/44\/\/2015-07-16\/2dcdeg.jpg",
"title": "second",
}];
}
validated json data:
{
"cat":{
"id":"1234567",
"source_id":null,
"title_en":"first season",
"description_en":"This is spring category "
},
"videos":[
{
"id":"312412343",
"url":"\/2015-07-17\/1abcd.mp4",
"img":"image\/44\/\/2015-07-17\/1abcd.jpg",
"title":"first"
},
{
"id":"2342343",
"url":"\/2015-07-16\/2dcdeg.mp4",
"img":"images\/44\/\/2015-07-16\/2dcdeg.jpg",
"title":"second"
}
]
}
Because you call
$data = json_decode($code2, true);
your $data is an array and not an object as you try to access it. So either access it as regular array, or change 2nd argument of json_decode() to false (or removeit as this is default), as this is what controls conversion behavior.
See docs: http://php.net/manual/en/function.json-decode.php
Your data is not a valid JSON (; at the end, redundant and missing comas - it's simply broken).
In case of such problems, var_dump() is pretty helpful to inspect what data you are really working with.

How to return the main nodes of json as array of object?

I have created this code:
$lists = $this->db->select("SELECT * FROM LOGGER");
$results = array();
$results['information'] = array();
$informations = $this->db->select("SELECT * FROM INFO WHERE code = :ccode", array("ccode" => "3"));
foreach($informations as $item)
{
$results['information'][] = $item;
}
$response = array(
"stack" => $lists,
"information" => $results['information']
);
if(!empty($response['details']))
{
return '{"logger": ' . json_encode(array_values($response)) . '}';
}
I take a stack information from my database and create two arrays. The first save all the informations stack that you can see below; the second array save only the description of the stack. Later I create a result array that save in each index stack and information the result of the two query. Now the final result is this:
{
"logger": {
"stack": {
"Code": "RB01",
"Descri": null,
"Created": "2016-03-09 04:36:04"
},
"information": [
{
"Id": "RB01",
"numeric": 1
},
{
"Id": "RB01",
"numeric": 2
},
{
"Id": "RB01",
"numeric": 3
}
]
}
}
but my goal is create a structure like the following:
{
"logger": [
{
"stack": [
{
"Code": "RB01",
"Descri": null,
"Created": "2016-03-09 04:36:04"
}
],
"information": [
{
"Id": "RB01",
"numeric": 1
},
{
"Id": "RB01",
"numeric": 2
},
{
"Id": "RB01",
"numeric": 3
}
]
}
]
}
which change I should do in my code?
For me, you should just change:
return '{"logger": ' . json_encode(array_values($response)) . '}';
with :
return '{"logger": ' . json_encode(array($response)) . '}';
It looks like you are just wrapping the object in another array?
if(!empty($response['details']))
{
$encoded = array(array_values($response));
return '{"logger": ' . json_encode($encoded) . '}';
}
Also, it is generally safer to create a new array json_encode that than writing your own json.
if(!empty($response['details']))
{
$encoded = array(array_values($response));
$result = array(
'logger' => array(array_values($response)),
);
return json_encode($result);
}

How to access multi-level json tree in PHP for database insertion

I am accessing an API where the JSON data is returned as below.
{
"name": "",
"count": 4,
"frequency": "",
"version": 3,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "",
"results": {
"collection": [{
"textlink": {
"href": "http://text1.com",
"text": "Text 1"
},
"index": 1,
"url": ""
}, {
"textlink": {
"href": "http://text2.com",
"text": "Text 2"
},
"index": 2,
"url": ""
}, {
"textlink": {
"href": "http://text3.com",
"text": "Text 3"
},
"index": 3,
"url": ""
}, {
"textlink": {
"href": "http://text4.com",
"text": "Text 4"
},
"index": 4,
"url": ""
}]
}}
As you can see the JSON tree returned has multi-step levels. I am wanting to be able to take some of the deeper levels, in PHP, and insert into a database.
Currently I am using this code to try and echo the data (once I am able to I can then work on inserting it to a database no problem)
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);
foreach($results as $item) {
echo $item->results[0]->collection[0]->textlink[0]->href;
echo "<br>";
echo $item->results->collection['href'];
echo "<br>";
echo $item->results->collection['text'];
}
?>
As you can see above I have tried several ways to access the deeper levels f data that are being displayed but with no avail.
I am currently getting errors of 'trying to get property of a non-object'. How is it possible to reach the data in this array?
try:
echo $results['results']['collection'][0]['textlink']['href'];
$obj = json_decode( $json, true ); foreach ( $obj['key'] as $key => $value ) { echo $value; }
foreach ($response['results']['collection'] as $textlink) {
$row = $textlink['textlink'];
echo $row['href'];
echo "<br>";
echo $row['text'];
echo "<br>";
}
you can do foreach like this, which loops only items in collection
I would suggest to do something like this (According to me, correct way to fetch results from API responses):
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$response = json_decode($response);
foreach($response->results->collection as $item) {
echo $item->textlink->href;
echo "<br>";
echo $item->textlink->text;
echo "<br>";
echo $item->index;
echo "<br>";
echo $item->url;
}
?>

Loop through JSON with php, and write to it. Output is null

My goal is to loop through each Item within the JSON and add an additional key called "modal" to each "Item", and the value paired with that key that would contain html. I stripped down my code below.
I'm able to add 'modal' to each 'Item', however the value somehow gets set to null, instead of the html I would like it to be.
JSON file:
{"Item":{
"thumbnail":"http://...",
"title": "Item title"
},
"Item":{
"thumbnail":"http://...",
"title": "Item title"
}}
php:
$json_a=json_decode($json, true);
foreach ($json_a['Item'] as &$obj){
$out = '<img src=\"' . $obj['thumbnail'] . '\">';
$out .= '<span>' . $obj['title'] . '</span>';
$obj['modal'] = $out; //value of $out doesn't get passed in, instead the value becomes null.
}
$json_a=json_encode($json_a);
print_r($json_a);
json output:
...{'modal': null}...
Edited the JSON to be valid. It comes from Amazon's product API, I shortened it for this example and made it invalid.
Your JSON is invalid. It is an object with duplicate keys ("Item"). You should use an array instead:
[
{
"thumbnail": "...",
"title": "..."
},
{
"thumbnail": "...",
"title": "..."
}
]
Then you can iterate over it and add 'modal' to all elements:
$json_a = json_decode($json, true);
foreach ($json_a as &$obj) {
$out = '<img src=\"' . $obj['thumbnail'] . '\">';
$out .= '<span>' . $obj['title'] . '</span>';
$obj['modal'] = $out;
}
$json_a = json_encode($json_a);
print_r($json_a);
Its simple your json is not valid
{
"Item": {
"thumbnail": "http://...",
"title": "Item title",
^---- This should not be here
},
"Item": {
^-------------- Duplicate name
"thumbnail": "http://...",
"title": "Item title",
^---- This should not be here
}
}
The main issue is that you need to generate your object or array properly using json_encode if you are using PHP for the generation

Categories