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);
Related
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;
I have example array of my data and I have to insert it into Google Charts with json. But I'd like to know how could make each Json data row with loop, so if I don't have that specific value defined I won't get an error.
$dataArray=array('item1;item2;item3;item4;item5','item2;item4;item3','item2;item3','item5;item4','item1;item4;item2');
$arrayOUT = [];
foreach ($dataArray as $a) {
$t = explode(";", $a);
foreach ($t as $y) {
if (!isset($arrayOUT[$y])) {
$arrayOUT[$y] = 0;
}
$arrayOUT[$y] += 1;
}
}
At the moment I have static json rows:
echo '{
"cols": [
{"id":"","label":"Data","pattern":"","type":"string"},
{"id":"","label":"Count","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"item1","f":null},{"v":'.$arrayOUT['item1'].',"f":null}]},
{"c":[{"v":"item2","f":null},{"v":'.$arrayOUT['item2'].',"f":null}]},
{"c":[{"v":"item3","f":null},{"v":'.$arrayOUT['item3'].',"f":null}]},
{"c":[{"v":"item4","f":null},{"v":'.$arrayOUT['item4'].',"f":null}]},
{"c":[{"v":"item5","f":null},{"v":'.$arrayOUT['item5'].',"f":null}]}
]
}';
But I would like to have rows done with loop. So for example, if I dont have item4 in my array, it wont create this row. So it only creates rows with existing data.
echo '{
"cols": [
{"id":"","label":"Data","pattern":"","type":"string"},
{"id":"","label":"Count","pattern":"","type":"number"}
],
"rows": [
Loop this row to create dynamic rows
{"c":[{"v":"item","f":null},{"v":'.$arrayOUT['item'].',"f":null}]},
]
}';
You can create a loop over the arrayOUT object.
I edited your example:
$dataArray=array('item1;item2;item3;item4;item5','item2;item4;item3','item2;item3','item5;item4','item1;item4;item2');
$arrayOUT = [];
foreach ($dataArray as $a) {
$t = explode(";", $a);
foreach ($t as $y) {
if (!isset($arrayOUT[$y])) {
$arrayOUT[$y] = 0;
} else {
$arrayOUT[$y] += 1;
}
}
}
$rows = "";
forEach($arrayOUT as $item=>$count){
$rows = $rows."{'c':[{'v':'{$item}','f':null},{'v':'{$count}','f':null}]},";
}
echo '{
"cols": [
{"id":"","label":"Data","pattern":"","type":"string"},
{"id":"","label":"Count","pattern":"","type":"number"}
],
"rows": [
'.$rows.'
]
}';
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'];
}
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
I was trying to parsing json file below from a link but I still can't figure it out about parsing and display it with foreach.
data: [
{
id: "1072",
nik: "013977",
status: "",
name: "RAKHMAT KUSNADI",
birthdate: "1983-10-21",
email: "rakhmat.koes#gmail.com",
first_login: "0",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1102",
employee_id: "1072",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
{
id: "1069",
nik: "013377",
status: "",
name: "RENATA MARINGKA",
birthdate: "1987-05-20",
email: "",
first_login: "1",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1099",
employee_id: "1069",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
]
}
I want to display name and profile_pics where department id is 101.
Does anybody know how to parse it with foreach?
Reinventing the wheel, are we? Why not simply use:
$jsonObj = json_decode($jsonString);//returns stdClass instance, just an object
$jsonArr = json_decode($jsonString, true);//converts object to associative array
Read more on json_decode here... It's quite easy to use, really
If you decode the data to an array, you could loop through the data like so
while($item = array_shift($jsonArr))
{
foreach ($item as $key => $value)
{
echo $key.' => '.$value."\n";
}
}
Or simply use any old for/foreach loop on an object, its a traversable object anyway (though it doesn't implement the Traversable interface)
First step is to convert to an array
$data = json_decode($json);
Once you've got the array, you can then loop through it and check the values
$keepers = array();
foreach ($data as $item) {
if ($item->placement->department_id == 101) {
$keepers[] = $item;
}
}
Use json_decode
$arr = json_decode($jsonstring, true);
then use foreach loop
foreach($arr as $val) {
if($val['placement']['department_id'] == "101") {
//display what u want
}
}
Probably something like:
$data = json_decode($your_json);
foreach($data as $object) {
echo 'This is the name: ' . $object->name . PHP_EOL ;
}
$data = json_decode($json, true)
Then whatever info you want out you get out with the foreach loop
foreach ($data->id as $id)
{
echo $id;
}
With that you can set any variable like $data->nik as $nik or whatever you want then echo them back
usr this
foreach ($data->id as $id)
{
echo $id;
}