JSON Decode not showing results - php

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.

Related

make json array in json codeigniter

please help, i got stucked on making json using codeigniter.
this is what i want my json look like
{
"pelajar": [
{
"id": "1",
"name": "rumah sakit",
"usia": "45",
"tahun": "2020",
"alamat": "jalan kartini"
},
{
"id": "2",
"name": "rumah sakit umum",
"usia": "28",
"tahun": "2020",
"alamat": "jalan ibu",
"pendidikan": [
{
"id_pelajar": "2",
"sekolah": "SDN Lombok timur"
},
{
"id_pelajar": "2",
"sekolah": "SMPN Lombok timur"
}
]
}
]
}
but, i dont know why my code doesnt work to make like it.
this is how my code output :
{
"pelajar": {
"pelajar": [
{
"id": "1",
"name": "rumah sakit",
"usia": "45",
"tahun": "2020",
"alamat": "jalan kartini"
},
{
"id": "2",
"name": "rumah sakit umum",
"usia": "28",
"tahun": "2020",
"alamat": "jalan ibu"
}
],
"pendidikan": [
{
"id_pelajar": "2",
"sekolah": "SDN Lombok timur"
},
{
"id_pelajar": "2",
"sekolah": "SMPN Lombok timur"
}
]
}
}
this is my code :
$query = $this->db->query("select * from learn") -> result();
$response = array();
$data = array();
$datap = array();
foreach($query as $row){
$data[] = array(
"id"=> $row->id,
"name"=>$row->name,
"usia"=>$row->usia,
"tahun"=>$row->tahun,
"alamat"=>$row->alamat
);
$id = $row->id;
$pendidikanquery = $this->db->query("select * from pendidikan where learn_id='$id'" ) -> result();
foreach($pendidikanquery as $pen){
$datap[] = array(
"id_pelajar"=> $pen->id_pelajar,
"sekolah"=> $pen->sekolah
);
}
}
}
$response['pelajar']['pelajar'] = $data;
$response['pelajar']['pendidikan'] = $datap;
header('Content-Type: application/json');
echo json_encode($response, TRUE);
my problem is to set 'pendidikan' in the pelajar list where id_pelajar from pendidikan is same with id from pelajar table.
Honestly, there is so much to fix, this script should probably be completely rewritten, but I am not prepared to do that from my phone.
I would recommend using Active Record techniques in your model (not your controller).
Cache the subarray data before pushing into the first level. In doing so, you maintain the relationship between the parent id and the subarray data.
To be clear, my snippet will always create a pendidikan subarray -- even if it has no data. If you do not want this behavior, you will need to modify the script to check if the subarray is empty and then conditionally include it into the parent array. If this was my project, I would prefer a consistent data structure so that subsequent process wouldn't need to check again if specific keys exist.
Untested code:
$query = $this->db->query("SELECT * FROM learn")->result();
$data = [];
foreach($query as $row){
$datap = [];
$pendidikanquery = $this->db->query("SELECT * FROM pendidikan WHERE learn_id = {$row->id}")->result();
foreach ($pendidikanquery as $pen) {
$datap[] = [
"id_pelajar" => $pen->id_pelajar,
"sekolah" => $pen->sekolah
];
}
$data[] = [
"id" => $row->id,
"name" => $row->name,
"usia" => $row->usia,
"tahun" => $row->tahun,
"alamat" => $row->alamat,
"pendidikan" => $datap
];
}
header('Content-Type: application/json');
echo json_encode(["pelajar" => $data]);
if you want the output like your first image(the one with a red square)-
$response['pelajar']['pendidikan'] = $datap; // change this one to
// this ↓↓
$response['pelajar']['pelajar']['pendidikan'] = $datap; // change it like this

Remove JSON Field In MySQL [PHP] [CodeIgniter]

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.

How to decode this json with foreach

This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>

How to split and change the json format

I am using slimphp v2 and I have the following function
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db - > prepare($sql);
$stmt - > execute();
$gs = $stmt - > fetchAll(PDO::FETCH_OBJ);
if ($gs) {
$db = null;
echo json_encode($gs, JSON_UNESCAPED_UNICODE);
} else {
echo "Not Found";
}
} catch (PDOException $e) {
echo '{"error":{"text":'.$e - > getMessage().
'}}';
}
}
The default json output looks like:
[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]
and the output that i am trying to make. I need to generate an ID: 1_(id) then format it like this
[{
id: "1",
task: "test",
}, {
ID: "1_1", //generate this, add 1_id
categoryId: "1",
mobile: "00000",
}, {
id: "2",
task: "test2",
}, {
ID: "1_2", //generate this, add 1_id
categoryId: "2",
mobile: "11111"
}];
Is it possible?
Thanks
I'm not sure if this is exactly what your after but you can gain the desired JSON output by converting your original JSON into an associative array and then restructure the data on each iteration using a Foreach() loop into a new assoc array. After that, you can just convert it back to JSON using json_encode().
Code:
$json = '[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]';
$jsonArr = json_decode($json, TRUE);
$newArr = [];
foreach ($jsonArr as $v) {
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
$newJson = json_encode($newArr);
var_dump($newJson);
Output:
[{
"id:": "1",
"task:": "test"
}, {
"ID:": "1_1",
"categoryId": "1",
"mobile": "111"
}, {
"id:": "2",
"task:": "test2"
}, {
"ID:": "1_2",
"categoryId": "2",
"mobile": "222"
}]
Edit -- Updated Answer
As discussed in comments, your outputting your SQL array as an object. I've set the Fetch to output as an associative array using PDO::FETCH_ASSOC and changed the foreach() loop to reference the assoc array $gs. This should work but if not then output your results for $gs again using var_dump($gs). You will still need to encode to JSON if needed but this line has been commented out.
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db->prepare($sql);
$stmt->execute();
$gs = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch as Associative Array
if ($gs) {
$db = null;
$newArr = [];
foreach ($gs as $v) { //$gs Array should still work with foreach loop
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
//$newJson = json_encode($newArr); //JSON encode here if you want it converted to JSON.
} else {
echo "Not Found";
}
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

PHP get array items based on string mask

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;
}

Categories