PHP loop for JSON rows - php

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

Related

How do I count Json data in PHP and get the answer in numbers

I have some trouble with making a loop that counts all the items in my API (json code). I have tried multiple loops that would count the items. But for you to understand what I am talking about I will first show you what I get with my API response.
{ "data": {
"boards": [
{
"groups": [
{
"id": "new_groupxxxx",
"title": "x"
}
],
"items": [
{
"name": "x",
"id": "xxxxxxxxx",
"state": "active"
}
This is what I get when I echo my code, I get a lot more items of course but I show you one for an example. I am trying to make a loop that counts all the "items" and brings them back to me with a total number that I then can put in my html table. See the thins I tried below.
$data = count($data); for($i = 0; $i < $data; $i++) {
if $i == $data
{
echo json_decode($responseContent);
console.log($query);
}
}
$data = count($data) $i = 0; foreach ($data["items"] as $value) {
if($value["id"] != $i){
$i < $value; $i++;
echo json_encode($responseContent);
console.log($query);
}
}
Your "items" are inside object which is an element of "boards" array. If you need to count all the items then you may need to loop through "boards" array.
Example
<?php
$data=json_decode(YOUR_API_RESPONSE)
$itemCount=0;
foreach($data->data->boards as $board) {
$itemCount+=count($board->items);
}
echo "Total number of items =".$itemCount;

Problem using a for loop in a PHP nested array to it into separate arrays

Am working on a nested array in PHP (From an API) which is 4 levels deep. Am trying to use a for loop to separate/dissect the nested arrays so that they may exist as independent entities so that I may use them in the blade. e.g agency_sales , unit_sales, agents When I dd on the browser, I get agency_sales while unit_sales I only get one array..
They are stored in a variable called rsm
The array collection
"regional_sales": [
{
"id": "75875",
"agency_sales": [
{
"id": "157",
"unit_sales": [
{
"id": "777",
"agents": [
{
"agent_no": "75939",
"policies": [
"IL*********"
]
},
{
"agent_no": "75939",
"policies": [
"IL**********"
]
}
]
},
{
"id": "111",
"agents": [
{
"agent_no": "758",
"policies": [
"IL2*********"
]
},
{
"agent_no": "75939",
"policies": [
"IL20**********"
]
}
]
}
]
}
]
}
]
My For loop
for($a=0; $a < count($rsm); $a++){
$asm = $rsm[$a]['agency_sales'];
//dd($asm);
for($b = 0; $b < count($asm); $b++){
$usm = $asm[$b]['unit_sales'];
dd($usm);
for($c = 0; $c < count($usm); $c++){
$ag = $usm[$c]['agents'];
//dd($ag);
}
}
}
I think you actually want to collect all the pieces at each level separately and then push down to generate the next level arrays. That will ensure you get all the values at each level into their respective array. This should work:
$asm = array();
for($a=0; $a < count($rsm); $a++){
$asm = array_merge($asm, $rsm[$a]['agency_sales']);
}
print_r($asm);
$usm = array();
for($b = 0; $b < count($asm); $b++){
$usm = array_merge($usm, $asm[$b]['unit_sales']);
}
print_r($usm);
$ag = array();
for($c = 0; $c < count($usm); $c++){
$ag = array_merge($ag, $usm[$c]['agents']);
}
print_r($ag);
I've omitted the output as it is quite long but you can see it on the demo on 3v4l.org
You should use foreach to parse through such an array:
foreach ($data['regional_sales'] as $regional_sale) {
// Access $regional_sale['id'] or anything else
foreach ($regional_sale['agency_sales'] as $agency_sale) {
// Access $agency_sale['id'] or anything else
foreach ($agency_sale['unit_sales'] as $unit_sale) {
// Access $unit_sale['id'] or anything else
foreach ($unit_sale['agents'] as $agent) {
// Access $agent['agent_no'] or anything else
}
}
}
}
Demo: https://3v4l.org/q3dAR

Combine two arrays two one and set keys

I have been struggling with this for quite some time. I have two arrays, which I need to combine.
This is my input:
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
Now the structure is, that each item in each array follows each other. So, the result should be something like:
{
"result": [
{
"mrn" : "18DK00310020B11A84",
"shipper" : "1861575"
},
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
]
}
However I simply cannot figure out how to do this.
I have tried to merge the two original arrays:
//Input
$array_one = $request->array_one;
$array_two = $request->array_two;
//Merge the two received arrays
$final = array_merge_recursive($array_one, $array_two);
However, this just removes array_one and array_two, but the array is still split up.
How can I combine above array, so it will have below format:
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
You can do this with some custom code:
$array_one = $request->array_one;
$array_two = $request->array_two;
$final = array_map(function ($value, $key) use ($array_two) {
foreach ($value as $k => $v) {
return [
"mrn" => $v,
"shipper" => array_get($array_two, "shipperreference.$key.$k")
];
}
}, array_get($array_one, 'mrnreference'), array_keys(array_get($array_one, 'mrnreference')));
A very quick solution to this would be just to iterate through a for loop.
for($i = 0; $i < count($array_one); $i++){
$final[$i]["mrn"] = $array_one["mrnreference"][$i]; // Mrn key equals array one value
$final[$i]["shipping"] = $array_two["shipperreference"][$i]; // Shipping key equals array two value
}
However, this has a small caveat that it could lead to an error, if $array_one and $array_two are not the same size.
First of all array_map can be used to get the values and then in simple for loop you can combine them. Notice that the size of mrnreference and shipperreference must be the same otherwise it will pop notice
$json = '
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
';
$arr = json_decode($json, true);
$ref = array_map(function($e){return $e['key_0'];}, $arr['array_one']['mrnreference']);
$ship = array_map(function($e){return $e['key_0'];}, $arr['array_two']['shipperreference']);
$output = array();
for ($i = 0, $cnt = count($ref); $i < $cnt ; ++$i) {
$output[] = [
'mrn' => $ref[$i],
'shipper' => $ship[$i],
];
}
echo json_encode(['result' => $output]);

How to get data from multi dimensional array

( Full pastebin: https://pastebin.com/C4qV5YYv)
I'm trying to select data from a (long) multi dimensional array, but with all things I tried the page just showed as blank. I'm trying to access the data with the name instead of it's rank in the list.
{
"playerstats": {
"steamID": "76561198035223060",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 38694
},
{
"name": "total_deaths",
"value": 33362
},
{
"name": "total_time_played",
"value": 2148546
},
{
"name": "total_planted_bombs",
"value": 770
},
{
"name": "total_defused_bombs",
"value": 271
},
{
"name": "total_wins",
"value": 12394
}, So on and so on......
I'm currently using this to get data from the array: $kills = $jsonforgame['playerstats']['stats'][0]['value'];
This works when you only need a couple of values, but it gets really tidy when I need to select values further down, like; $hit = $jsonforgame['playerstats']['stats'][47]['value'];
Is there anyway for me to select the stats with the name, like this: $hit = $jsonforgame['playerstats']['stats']['total_shots_fired']['value']; instead of the number.
Thanks in advance.
You may go for something like this:
function getStat($data, $name)
{
return array_filter($data, function($item) use ($name) {
return $item && $item['name'] === $name;
})[0]['value'];
}
$hit = getStat($jsonforgame['playerstats']['stats'], 'total_shots_fired');
But the more efficient way would be to change your stats api so it serves key-value pairs, if it is possible, ofc.
One way would be to change how you create the array as so:
{
"playerstats": {
"steamID": "76561198035223060",
"gameName": "ValveTestApp260",
"stats":
{
"total_kills": 38694,
"total_deaths": 33362,
"total_time_played": 2148546,
...
}
then simply access by $kills = $jsonforgame['playerstats']['stats']['total_kills']
In case you can't change the array, you could also try
$specs = array("total_kills", "total_deaths", "total_time_played"); // and so on
foreach ( $specs as $spec )
$$spec = $jsonforgame['playerstats']['stats'][ $spec ]['value'];
After that you can use each spec by name, for example $total_kills
If you want to use shorter variable names you can change the code like this
$specs = array(
"kills" => "total_kills",
"died" => "total_deaths",
"played" => "total_time_played"
); // and so on
foreach ( $specs as $key => $spec )
$$key = $jsonforgame['playerstats']['stats'][ $spec ]['value'];
echo $kills; // output $jsonforgame['playerstats']['stats']['total_kills']['value']
Another approach
$count = count($jsonforgame['playerstats']['stats']);
for ( $i = 0; $i < $count; $i++ ) {
$name = $jsonforgame['playerstats']['stats'][ $i ]['name'];
$value = $jsonforgame['playerstats']['stats'][ $i ]['value'];
$$name = $value;
}
and with use of the array with shorter variable names
$specs = array(
"total_kills" => "kills",
"total_deaths" => "died",
"total_time_played" => "played",
); // and so on
$count = count($jsonforgame['playerstats']['stats']);
for ( $i = 0; $i < $count; $i++ ) {
$name = $specs[ $jsonforgame['playerstats']['stats'][ $i ]['name'] ];
$value = $jsonforgame['playerstats']['stats'][ $i ]['value'];
$$name = $value;
}

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

Categories