How to convert JSON string to arrays - php

With php, I need to convert json arrays into arrays, what should I do, json_encode didn't work for me, thanks in advance for help.
//json sequence
[
{
"name":"Menu",
"sub":
[
{
"name":"Menu 2",
"url":"menu-2.php"
}
]
}
]
this way i should do
array(
'name' => 'Menu',
'sub' => array(
array(
'name' => 'Menu 2',
'url' => 'menu-2.php'
)
)
)
i am creating json array with this function
Do I have to make a change here? I'm not really good in arrays.
<?php
$connect = new PDO("mysql:host=localhost; dbname=propanel_001", "root", "");
$parent_category_id = "";
$query = "SELECT * FROM tb_sayfalar";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$data = get_node_data($parent_category_id, $connect);
}
echo json_encode(array_values($data));
function get_node_data($parent_category_id, $connect)
{
$query = "SELECT * FROM tb_sayfalar WHERE parent_id = '".$parent_category_id."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$sub_array = array();
if (array_values(get_node_data($row['id'], $connect))) {
$sub_array['name'] = $row['page_name'];
$sub_array['sub'] = array_values(get_node_data($row['id'], $connect));
}else{
$sub_array['name'] = $row['page_name'];
$sub_array['url'] = $row['page_url'].".php";
}
$output[] = $sub_array;
}
return $output;
}
?>

This is what you need, json_decode($json,true);
<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = json_decode($json,1);
print_r($array[0]);
?>
DEMO: https://3v4l.org/JZQCn
OR use it as a parsable string representation of a variable with var_export()
<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = var_export(json_decode($json,1)[0]);
print($array);
?>
DEMO: https://3v4l.org/rLA9R

You must use json_decode to convert JSON representing Object to Associative array.
Example Code
$resArr = json_decode($response, true);
For more information look at PHP JSON_DECODE

Related

How can I encode a json of a multiline result?

I try to encode my result in a json but it doesn't really work. When the query has more than one result than it doesn't work. When the result has only one line, than everything works fine.
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query ($db, "SELECT a, b FROM table WHERE a LIKE '%{$query}%' OR b LIKE '%{$query}%'");
$array = array();
while ($row = mysqli_fetch_assoc($sql)) {
$array[] = array (
'label' => $row['a'].', '.$row['b'],
'value' => $row['a'],
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
}
Try this code
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query ($db, "SELECT a, b FROM table WHERE a LIKE '%{$query}%' OR b LIKE '%{$query}%'");
$array = array();
$i = 0;
while ($row = mysqli_fetch_assoc($sql)) {
$array[$i] = array (
'label' => $row['a'].', '.$row['b'],
'value' => $row['a'],
);
$i++;
}
//RETURN JSON ARRAY
echo json_encode ($array);
}

make foreach into json array

I'm a little confused, and I need help.
I have a foreach loop in my code below. I need to put the foreach loop into the $data = array('image' => $final_image);
How can i put foreach loop in array ? Anyone can help me please.
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
}
echo $final_image;
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_image,
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
// Create an array to store final images
$final_images = [];
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
// Save the image if its new data.
$final_images[]= $final_image;
}
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_images, // We pass the final images array
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
Made things a bit more verbose.
First define the array.
Then in the if statement add element to the array.
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
$final_images = array(); // Define object as array
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
$final_images[] = array('image' => $final_image); // Will create new array item
}
echo $final_image;
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_image,
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}

PHP how to make one sqaure bracket for all json object

The below is my php code.Many thanks
$data = array();
foreach ($row as $rowk) {
$data[] = array(
'message' => $row['traditionalmessage'],
'phone' => $row['telMobile']
);
break;
}
echo json_encode($data);
My current result
[{"message":"B\u578b\u809d\u708e\u75ab\u82d7\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"}][{"message":"\u75ab\u82d7\u540d\u7a314\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"}][{"message":"\u4fe1\u606f","phone":"55503234"}]
My desired result
[{"message":"B\u578b\u809d\u708e\u75ab\u82d7\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"},{"message":"\u75ab\u82d7\u540d\u7a314\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"},{"message":"\u4fe1\u606f","phone":"55503234"}]
In JSON arrays represented in [], and objects in {}, so in desired case you should have array of objects while you have array of arrays.
Try something like this:
$data = array();
foreach ($row as $rowk) {
$obj = new stdClass();
$obj->message = $row['traditionalmessage'];
$obj->phone = $row['telMobile'];
$data[] = $obj;
}
echo json_encode($data);

change php sql results array format to json format with customized labels and values

I need help in converting this json data array
{"Untracked":4,"Available":3,"Groups":"4","Users":"5"}
to this type of json
[{"label":"Untracked","value":"4"},
{"label":"Available","value":"3"},
{"label":"Groups","value":"4"},
{"label":"Users","value":"5"}
]
my method is
public function graphs(){
$company_id =$this->session->userdata('itms_company_id');
$data['Untracked'] = $this->mdl_fetch->count_untracked_assets ($company_id);
$data['Available'] = $this->mdl_fetch->count_available_devices ($company_id);
$data['Groups'] = $this->mdl_fetch->count_unassigned_groups($company_id);
$data['Users'] = $this->mdl_fetch->count_unassigned_users($company_id);
echo json_encode($data);
}
Try this :
public function graphs(){
$company_id =$this->session->userdata('itms_company_id');
$data[] = array( 'label' => 'Untracked', 'value' => $this->mdl_fetch->count_untracked_assets ($company_id));
$data[] = array( 'label' => 'Available', 'value' => $this->mdl_fetch->count_available_devices ($company_id));
$data[] = array( 'label' => 'Groups', 'value' => $this->mdl_fetch->count_unassigned_groups($company_id));
$data[] = array( 'label' => 'Users', 'value' => $this->mdl_fetch->count_unassigned_users($company_id));
echo json_encode($data);
}
This is one way, but it seems a little long winded.
The json {} indicates you want an object, so you can use the simple PHP stdClass() and add the relevant properties and get the data from the array returned by your mdl->fetch's and load the object. Then just add it to the $data array.
public function graphs(){
$company_id = $this->session->userdata('itms_company_id');
$d = $this->mdl_fetch->count_untracked_assets ($company_id);
$o = new stdClass();
$o->label = 'Untracked';
$o->value = $d['Untracked'];
$data[] = $o;
$d = $this->mdl_fetch->count_available_devices ($company_id);
$o = new stdClass();
$o->label = 'Available';
$o->value = $d['Available'];
$data[] = $o;
$d = $this->mdl_fetch->count_unassigned_groups($company_id);
$o = new stdClass();
$o->label = 'Groups';
$o->value = $d['Groups'];
$data[] = $o;
$d = $this->mdl_fetch->count_unassigned_users($company_id);
$o = new stdClass();
$o->label = 'Users';
$o->value = $d['Users'];
$data[] = $o;
echo json_encode($data);
}
Here, is the example, which have same output
$a = array(); <br>
$a[0]['label'] = "Untracked"; <br>
$a[0]['value'] = "4"; <br>
$a[1]['label'] = "Available"; <br>
$a[1]['value'] = "3"; <br>
$a[2]['label'] = "Groups"; <br>
$a[2]['value'] = "4"; <br>
$a[3]['label'] = "Users"; <br>
$a[3]['value'] = "3"; <br>
$json= json_encode($a); <br>
<b>Output</b> <br>
[{"label":"Untracked","value":"4"},<br>{"label":"Available","value":"3"},<br>{"label":"Groups","value":"4"},<br>{"label":"Users","value":"3"}]<br>
So, you can write a function like this:
function graphs(){
$company_id =$this->session->userdata('itms_company_id');<br>
$data[0]["lable"] = "Untracked";<br>
$data[0]['value'] = $this->mdl_fetch->count_untracked_assets ($company_id);<br>
$data[1]["lable"] = "Available";<br>
$data[1]["value"] = $this->mdl_fetch->count_available_devices ($company_id);<br>
$data[2]["lable"] = "Groups";<br>
$data[2]["lable"] = $this->mdl_fetch->count_unassigned_groups($company_id);<br>
$data[3]["lable"] = "Users";<br>
$data[3]["lable"] = $this->mdl_fetch->count_unassigned_users($company_id);<br>
echo json_encode($data);
}
No need to change entire function.
Change from echo json_encode($data); to return json_encode($data);.
Create a function that change format from one json to another after calling a graph() function you can call another function that can return a json data as like you want
function changeFormat($js)
{
$jsArray = json_decode($js,true);
$result = array();
foreach($jsArray as $key=>$value)
{
$result[] = array("label"=>$key,"value"=>$value);
}
return json_encode($result);
}
echo changeFormat($js);

Json array add onto php array

I want to acheive something simliar to this adding elements onto an array but when I use this methods two nodes get created in the json element. I only want one node with all the entires within that also can you name nodes ie Properties.
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
$custom = array('name'=>'foo', 'id' => 'bar');
$data[] = $custom;
Try this code array_push is better option here,
<?php
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$temp = array();
$temp = array('name' => $row['name'], 'id' => $row['id']);
array_push($json, $temp);
}
$custom = array('name'=>'foo', 'id' => 'bar');
array_push($json,$custom);
?>

Categories