I have the following JSON file:
[
{
"1421999354744": {
"article_id": "213123",
"artfile_status": "",
"process_starttime": "2015\/01\/23 13:19:14",
"process": "Validator",
"process_endtime": "2015\/01\/23 13:19:14",
"process_status": "COMPLETED",
"sub_process_name": "",
"percentage_completed": "100",
"XML_Validity": "false",
"process_type": "AUTO"
}
},
{
"1421999527002": {
"article_id": "213123",
"artfile_status": "",
"process_starttime": "2015\/01\/23 13:22:06",
"process": "Validator",
"process_endtime": "2015\/01\/23 13:22:06",
"process_status": "COMPLETED",
"sub_process_name": "",
"percentage_completed": "100",
"XML_Validity": "false",
"process_type": "AUTO"
}
},
{
"1421999580405": {
"article_id": "213123",
"artfile_status": "",
"process_starttime": "2015\/01\/23 13:23:00",
"process": "Validator",
"process_endtime": "2015\/01\/23 13:23:00",
"process_status": "COMPLETED",
"sub_process_name": "",
"percentage_completed": "100",
"XML_Validity": "false",
"process_type": "AUTO"
}
}
]
I need to get the values of article_id in the above. I've tried to read the multiple dimension but it shows an error.
The code that I have is as follows:
foreach ($response as $key => $value) {
$t = $response[$i];
foreach ($t as $key1 => $value2) {
echo $t[$j]['article_id'];
$j++;
}
$i++;
}
The first array values will be dynamic.
Any help would be appreciated!
You do not need counters at all(in your case $i, $j). You can extract the value from the array by iterating over the array and extracting the data directly from the current value of the iterator:
foreach ($response as $key => $value) {
// Get the first value of the sub-array array,
// which is actually the array you want to extract values from
$value = current($value);
// Print out the article id value
// if your json has been decoded as an array use $value['article_id']
echo $value->article_id;
}
Related
I wrote a function to accept a 'product_id' and then it will cycle through all my Json fields to find all the json objects without the id 'product id' and then I need it encode it back and update database.
currently I substituted 'product_id' with '154' since that is a 'id' I am testing to remove.
This Foreach statement I wrote gets me all the ids
$user = $this->session->userdata('user_id');
$autoOrder = $this->db->get_where('auto_order', ['user_id' => $user])->row()->products;
$temp = json_decode($autoOrder);
foreach ($temp as $value) {
$last_value = (array)$value;
foreach ($last_value as $key=> $value) {
foreach($value as $key2=>$value2) {
if ($key2 == 'id' && $value2 != '154') {
echo "Product Id: " . $value2 . "<br>";
$new_ids[] = $value2;
}
}
}
}
How can I now cycle through all the autoOrder and retrieve only the ones with 'new_ids'?
Example How The JSON Looks:
[
{
"order": {
"id": "154",
"qty": "1",
"option": "{\"color\":{\"title\":\"Color\",\"value\":null}}",
"price": "2433.62",
"name": "Race Car",
"shipping": "0",
"tax": "26",
"image": "http://localhost/products/image/34",
"coupon": ""
}
}
]
This code you wrote it's a bit complicated to understand.
Anyway, you should save the new_ids into the DataBase, and then execute the query specifying the condition to retrieve only the object without new_ids on the WHERE.
i have an array with a bunch of records like in:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"typeID": "1",
"datein": "2016-09-26 12:14:16",
"edited_datein": null,
"publishDate": "2016-09-23 00:00:00",
"category": {
"ID": "1",
"heading": "News",
"typeID": "3",
"datein": "2016-09-26 11:50:06",
"edited_datein": null,
"url": "news"
},
"authorID": "592",
"tags": "skool,school,hoof,headmaster,etienne burger"
}
i have another array with "columns" i want the records to be "filtered" by
{
"ID",
"heading",
"datein",
"category|heading",
"category|url"
}
i would like the result to create a multidimensional array based on the column items:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"datein": "2016-09-26 12:14:16",
"category": {
"heading": "News",
"url": "news"
}
}
how do i achieve this? i'm totally stuck on this now :( busy trying a hack of array_combine now but i dont hold much hope it would work out
so after being stuck on this for many hours.. and posting it here. i found a solution
$new_list = array();
foreach ($n as $record) {
$new_list[] = filter_columns($columns, $record);
}
and the function:
function filter_columns($columns, $record, $pre="") {
$return = array();
foreach ($record as $key => $value) { // loop through the fields in the record
$str = $pre.$key; // create a string of the current key
if (in_array($str,$columns)){
$return[$key] = $value;
}
if (is_array($value)){
$return[$key] = filter_columns($columns, $value,$key."|"); // if the value is an array recall the function but prepend the current key| to the key mask
}
}
return $return;
}
I have a pretty simple bit of code to decode a json result:
code
$returnSK = returnSeoKicksLinks($s[0]);
echo "SeoKicks: " . $returnSK;
$seoKicks = json_decode($returnSK, true);
if (is_array($seoKicks) || is_object($seoKicks))
{
foreach ($seoKicks as $key => $val2)
{
$backlinks2 = $val2['UrlFrom'];
echo $backlinks2;
// backlink query and insertion
//$b = $c->query("INSERT INTO `backlinks` (`backlink_id`,`backlink_url`,`backlink_mother_url`,`backlink_date`,`backlink_from`) VALUES ('','".$backlinks2."','".$s[0]."','seokicks',NOW())");
}
}
The JSON results:
{
"Results": [
{
"Links": [
{
"Anchor": "guaranteed payday loan",
"nofollow": "1",
"UrlTo": "http:\/\/www.site.co.uk\/"
}
],
"Index": 1,
"IP": "67.139.134.215",
"UrlFrom": "http:\/\/menomena.com\/?p=240",
"DomainRank": "7"
},
{
"Links": [
{
"nofollow": "0",
"UrlTo": "http:\/\/www.site.co.uk\/",
"Anchor": "Cash Till Payday Loan"
}
],
"DomainRank": "6",
"IP": "67.222.22.156",
"Index": 2,
"UrlFrom": "http:\/\/www.aussi.org\/business\/financial-services\/loans\/"
},
{
"DomainRank": "6",
"UrlFrom": "http:\/\/www.loanranks.com\/improving-your-chances-of-receiving-payday-loans",
"Index": 3,
"IP": "173.254.28.69",
"Links": [
{
"Anchor": "guaranteed payday loans",
"nofollow": "0",
"UrlTo": "http:\/\/www.site.co.uk\/"
}
]
}
],
"Overview": {
"domainpop": "29",
"firstresultposition": 1,
"totalresultsreturned": 3,
"linkpop": "37",
"netpop": "27",
"ippop": "29"
}
}
I'm trying to get the "UrlFrom" value, but it's coming up blank, is there something i am missing here?
Without the first part of your code can not perform a test to figure out where he might be the problem. However, with this code I can print the value of UrlFrom field (passing the JSON in POST request):
$jsonPost = file_get_contents('php://input');
$decodedJson = json_decode($jsonPost);
foreach($decodedJson->Results as $key => $value) {
var_dump($value->UrlFrom);
}
You need to tell PHP to look in the "Results" array, like this:
foreach ($seoKicks['Results'] as $key => $val2)
So your code would become:
$seoKicks = json_decode($returnSK, true);
if (is_array($seoKicks) || is_object($seoKicks))
{
foreach ($seoKicks['Results'] as $key => $val2)
{
$backlinks2 = $val2['UrlFrom'];
echo $backlinks2;
// backlink query and insertion
//$b = $c->query("INSERT INTO `backlinks` (`backlink_id`,`backlink_url`,`backlink_mother_url`,`backlink_date`,`backlink_from`) VALUES ('','".$backlinks2."','".$s[0]."','seokicks',NOW())");
}
}
Some thoughts on SQL Injection
Before you uncomment the query part, please change your query to not concatenate values into the SQL. To avoid the risk of SQL injection, you should use prepared statements instead, binding the dynamic value(s) to it.
I have 2 records from 2 different query results. I have merged those data. but i have to display unique data depends on vName key.
Here is my result:
{
"val1": "9",
"vName": "abc",
"bname": "",
"cname": "",
"brid": "",
"cmpid": "154",
"logo": "",
"banner": "",
"description": "",
"catids": "",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "",
"compressthumb_logo": "",
"bigthumb_banner": "",
"compressthumb_banner": "",
"sp_ar": "Aperitif"
},
{
"val1": "9",
"vName": "abc",
"bname": "abc",
"cname": "abc",
"brid": "341",
"cmpid": "154",
"logo": "",
"banner": "6c497c72bfec4c694c1cc2c49066e7a1.png",
"description": "http:\/\/www.abc.com\/",
"catids": "9",
"sp_ar": "Aperitif",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "40cbcede9429cdb44895e0e6f4c050d2.png",
"compressthumb_logo": "40cbcede9429cdb44895e0e6f4c050d2.png",
"bigthumb_banner": "6c497c72bfec4c694c1cc2c49066e7a1.png",
"compressthumb_banner": "6c497c72bfec4c694c1cc2c49066e7a1.png"
}
Expected result should be only one of them, compare with vName:
{
"val1": "9",
"vName": "abc",
"bname": "",
"cname": "",
"brid": "",
"cmpid": "154",
"logo": "",
"banner": "",
"description": "",
"catids": "",
"type": "company",
"is_nav": "1",
"bigthumb_logo": "",
"compressthumb_logo": "",
"bigthumb_banner": "",
"compressthumb_banner": "",
"sp_ar": "Aperitif"
}
How can i get the result?
Convert the data into an array where the key is your unique value.
You can do something like:
$data = array('this is your array of data');
$unique = array();
foreach($data as $value) {
if(!array_key_exists($value['vName'], $unique)) {
$unique[$value['vName']] = $value;
}
}
// $unique now contains only arrays with a unique 'vName', using the first it finds in the original list
$new_array = array_values($unique);
Assuming you have a array of associative array stored in $data, the following code will filter it based on vName and store array of associative arrays with unique vName in $filtered_data
$taken = array();
$filtered_data = array_filter($data, function($value) {
global $taken;
if (in_array($value['vName'], $taken)) {
return false;
}
else {
$taken[] = $value['vName'];
return true;
}
});
Here, the variable $taken keeps track of all the vName values that are currently in the $filtered_data. If you find a duplicate vName (that is currently there in $taken), it discards that element.
Try this, it should work for you.
$input = array_map("unserialize", array_unique(array_map("serialize",$input)));
Im trying to get the values from the various sections of this json entry.
{
"gallery_show": "1",
"gallery": {
"path": ["images\/slide2.jpg", "images\/slide1.jpg", "images\/slide2.jpg", "images\/slide1.jpg", "images\/slide2.jpg", "images\/slide1.jpg"],
"title": ["", "", "", "", "", ""],
"caption": ["", "", "", "", "", ""],
"thumb": ["\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg"]
},
"videos_show": "1",
"videos": {
"title": ["Arnie", "Arnie", "Arnie", "Arnie", "Arnie"],
"sharelink": ["http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY"]
},
"attachments_show": "1",
"attachments": {
"path": ["images\/slide2.jpg", "images\/slide1.jpg"],
"title": ["Attchment", "Attchment"],
"caption": ["Attachment Description", "Attachment Description"]
},
"links_show": "1",
"links": {
"title": ["Link1", "Link2"],
"httplink": ["http:\/\/www.mydomain.com", "http:\/\/www.mydomain.com"],
"targetlink": ["_blank", "_blank"]
}
}
If i use this method
$entries= json_decode($this->item->entries);
and then i echo this
echo $entries->gallery_show;
I get the desired result = 1
But how do i now get the things beneath it if gallery_show=1 and display them as values i can use inside my php?
Any help for this old brain would be much appreciated.
Cheers in advance
Jonny
You could do somewhat like this...
$arr = json_decode($json);
foreach($arr as $k=>$v)
{
if($k=='gallery_show' && $v==1)
{
foreach($arr->gallery->path as $path)
{
echo "<img src=$path />";
}
break;
}
}
Demo
Code update..
$arr = json_decode($json);
$i=0;
foreach($arr as $k=>$v)
{
if($k=='gallery_show' && $v==1)
{
foreach($arr->gallery as $gall)
{
echo "Title :".$arr->gallery->title[$i]."<br/>";
echo "Caption :".$arr->gallery->caption[$i]."<br/>";
echo "Thumbnail :".$arr->gallery->thumb[$i]."<br>";
echo "<img src=".$arr->gallery->path[$i]." /><br>";
$i++;
}
break;
}
}
Demo