How to create JSON object in php without key name? - php

I am trying to create JSON Object and array in php. but It creates unwanted indexes (keys).Is there any way I can create object without Key name like $temp_obj-> No Key here $all_products_array; ???? Thanks in advance
This is How am I trying...
$combo_info = new stdClass();
$combo_info-> combo_id = $combo_id;
$combo_info-> combo_name = $combo_name;
$temp_obj = new stdClass();
for($i=0; $i<=16; $i++){
$all_products_array = array();
$all_products_array = array("product_id" => $product_id,"product_name" => $product_name);
$temp_obj->all_products_array_inside[$i] = $all_products_array;
}
$myObj = new stdClass();
$myObj->combo_info = $combo_info;
$myObj->all_products_array = $temp_obj;
$myfinalobj-> myfinalobj[$i] = $myObj;
header('Content-Type: application/json');
echo '['. json_encode($myfinalobj, JSON_PRETTY_PRINT) .']';
It will produce below result where index/key named "1" and "all_products_array_inside" are unwanted. Because I have to go myfinalobl->all_products_array->all_products_array_inside[1].product_id
but i want easy like myfinalobl->all_products_array[i].product_id
Is there any way I can create object without Key name like
$temp_obj-> No Key here $all_products_array; ????
{
"myfinalobj": {
"1": {
"combo_info": {
"combo_id": "1",
"combo_name": "Supper_deal",
},
"all_products_array": {
"all_products_array_inside": {
"1": {
"product_id": "1",
"product_name": "TV"
},
"2": {
"product_id": "2",
"product_name": "Laptop"
}
}
}
}
}
}

You are creating the key yourself (from $i), so just don't do that...
$myfinalobj->myfinalobj[$i] = $myObj;
Here you have [$i] - remove it:
$myfinalobj->myfinalobj = $myObj;

Related

fetching multiple rows and display in json

I have a PHP code like:
while ($row2 = mysqli_fetch_assoc($check2)) {
// $leadarray[] = $row2;
$service_id[$i] = $row2['service_id'];
$row1['service_id'][$i] = $service_id[$i];
$service_name[$i] = $row2['service_name'];
$row1['service_name'][$i] = $service_name[$i];
$i++;
}
$leadarray[] = $row1;
$trimmed1['leaddetails'] = str_replace('\r\n', '', $leadarray);
echo json_encode($trimmed1);
getting output like
{
"leaddetails": [
{
"service_id": [
"7",
"2"
],
"service_name": [
"Past Control Services",
"Civil Finishing"
],
}
]
}
I want output like:
"service_id": [
1: "7",
2: "2"
],
"service_name": [
1: "Past Control Services",
2: "Civil Finishing"
],
or
[
"service_id": "7",
"service_name": "Past Control Services",
"service_id": "2",
"service_name": "Civil Finishing",
]
$trimmed1 is considered an object when passing it to json_encode (associative array in PHP) because you explicitly give it a key (considered an object property in JSON):
$trimmed1 = [];
$trimmed1['leaddetails'] = 'foobar';
This will result in json_encode encoding $trimmed1 into an object:
{
"leaddetails": "foobar"
}
To get your desired result, have $trimmed1 be considered an ARRAY when passed to json_encode.
$trimmed1[] = str_replace('\r\n', '', $leadarray); // push instead of assign
second option is not posible
you can make like this
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
using class for make like that
class Data{
$service_id;
$service_name;
}
$obj = new Array();
while ($row2 = mysqli_fetch_assoc($check2)){
$data = new Data();
$data->service_id = $row2['service_id'];
$data->service_name = $row2['service_name'];
array_push($obj, $data);
}
echo json_encode($obj);
Create the 2-dimensional array first. Then push onto the nested arrays during the loop.
$result = ["service_id" => [], "service_name" = []];
while ($row2 = mysqli_fetch_assoc($check2)) {
$result["service_id"][] = $row["service_id"];
$result["service_name"][] = $row["service_name"];
}
echo json_encode($result);

How to correctly create and append data in a JSON Object using PHP?

I'm struggling on how to properly create a JSON file and append data to it, here's my PHP code:
<?php
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
$array = json_decode($jsonStr, true);
if ($array != null) {
$arrNew['ObjID']++;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$arrNew = [];
$array['ObjID'] = 0;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>
If I refresh the URL in my browser by calling my php file, I get this output if i go to example.com/_users.json
{
"0": [],
"1": {
"ObjID": 1,
"username": "bob",
"email": "b#doe.com"
},
"2": {
"ObjID": 1,
"username": "sarah",
"email": "b#doe.com"
},
"3": {
"ObjID": 1,
"username": "sarah",
"email": "b#doe.com"
},
"ObjID": 0,
"username": "bob",
"email": "b#doe.com"
}
So I'm able to generate a .json file, but what I need to do is a piece of code to do the following sequence:
Since the first time I run the script, the _users.json file doesn't exist, it needs to get generated
Create a JSON main object
Insert 1st object inside the main object
Append a 2nd object (still inside the main object)
And so on with 3rd, 4th, etc..
So I would need to get an output like this:
{ <-- Main Object starts
"1": { <-- 1st object inside the Main Object
"ObjID": 1,
"username": "bob",
"email": "b#doe.com"
},
"2": { <-- 2nd object
"ObjID": 1,
"username": "sarah",
"email": "s#doe.com"
}
} <-- Main Object closes
I can't really figure out what I'm doing wrong in my PHP code.
Logic in the else part should be inverted:
} else {
$array = [];
$arrNew['ObjID'] = 0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
}
Try below code.
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
if($jsonStr=='') $array = array();
else $array = json_decode($jsonStr, true);
if (empty($array)) {
$arrNew = [];
$arrNew['ObjID']=0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$array['ObjID'] ++;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>

Create Multidimentional json object from database

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

Foreach getting value null, why?

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

PHP json string: getting an associative array object

I have a json file with data like this (this is a partial view of the file to show structure):
{
"state": {
"ALABAMA": {
"ZOLD": [ "101", "102" ],
"ZNEW": [ "11", "12" ]
},
"ALASKA": {
"ZOLD": [ "5001", "5002", "5003", "5004", "5005", "5006", "5007", "5008", "5009", "5010"],
"ZNEW": [ "21", "22", "23", "24", "25", "26", "27", "28", "29", "20"]
}
}
}
What I want to do is search through it to find a value in the ZOLD field = $OLD, then return the value of the corresponding ZNEW array. I've tried going in with foreach and can get the arrays to echo out, but I'm not sure of what the value will be. Here's the code I have:
function translateZone($OLD)
{
$OLD = "5010"; //for testing purposes a constant but will be variable
$zStr = file_get_contents('getnew.json');
$zJson = json_decode($zStr,true);
foreach($zJson as $key=> $jsons)
{
foreach($jsons as $key=>$values)
{
foreach($values as $key=>$vals)
{
$counter=0;
foreach($vals as $key=>$vls)
{
$counter ++;
echo var_dump($vls);//I can see the values,but now what?
if ($vls == $OLD)
{
$zTemp = Help here -some array value of counter??
}
}
}
return $zTemp;
}
}
I've searched through a bunch of other questions but haven't found something close enough to help with the problem.
Additional information: I may or may not know the "state" string (i.e. "Alaska") but I may want to return this information as well based on the found value.
Thanks for the help.
Instead of trying to loop through ZOLD, you could use array_search (assuming that the $OLD value can only appear once in the data). This function will either return a number for the index of the value you search for or false if it cannot find it:
$index = array_search($OLD,$values['ZOLD']);
if ($index !== FALSE) {
$zTemp = $values['ZNEW'][$index];
}
This would replace your two innermost for loop (as you need the other loops to get down to this level) and iterate through each state. At this point as well, $key would be defined to your state name.
Here is another way to complete your task, this one with array_map function:
$jsonArray = json_decode($your_file_content, true);
$oldVal = "5005";
$result = [];
foreach( $jsonArray["state"] as $k => $v ) {
/**
* Here we're building an array or pairs ZOLD => ZNEW values
*/
$pairs = array_map(function($o, $n) {
return [ $o => $n ];
}, $v["ZOLD"], $v["ZNEW"]);
/**
* Filling up the result
*/
foreach( $pairs as $p )
if( isset($p[$oldVal]) )
$result[] = [
"state" => $k,
"ZNEW" => $p[$oldVal]
];
}
var_dump($result);
$result dump will contains a list or assoc arrays with "state" and "ZNEW" keys, if the corresponding ZNEW values will be found

Categories