PHP stdObject to array that can be used in Google Charts [duplicate] - php

This question already has an answer here:
Google Table Chart from php created Json
(1 answer)
Closed last year.
I would like to use google charts to visualize some data.
I know from documentation that in order to use google charts the data must be in the following form:
[["C1","C2","C3],[C1V1,C2V1,C3V1],[C1V2,C2V2,C3V3]]
Where c1-c3 are columns one to three and the same of v1-v3 for values.
I currently have data from a query in php in the following form:
Array ( [0] => stdClass Object ( [C1] => C1V1 [C2] => C2V1 [C3] => C3V3 ))
I am getting my data using a simple sql query in laravel:
$live = DB::connection('azure')->select("SELECT C1,C2 FROM tableName");
How can I convert from my data form to the one from the top so that I can use google charts.
I am using PHP so I would like to be able to convert it in that language.
Any help is greatly appreciated!

To format the data in source array $arr to fit your needs, you could use:
<?php
$i=0;
$newArr[0] = array_keys($arr[0]);
foreach($arr as $record) {
$i++;
foreach($record as $col => $val) {
$newArr[$i][] = $val;
}
}
working demo

You need to create the first inner array using the indexes returned from the DB. So if your database query returns an associative array you can use the array_keys function to get an array of all the keys, add that as the first entry in the your main array, then loop through your data returned from the database and add each row as a new entry in your main array.

Related

How to dynamically insert JSON data into a PHP array for foreach [duplicate]

This question already has answers here:
How to create a JSON object
(5 answers)
Closed 3 years ago.
I have the following PHP code, which gets executed when I hit the Submit button in a form:
// Save data
if(isset($_POST['save'])){
$newDataArr = array();
foreach ($data_array[0] as $k=>$v){
$newDataArr[] = array($k => $_POST[$k]);
}// ./ foreach
echo json_encode($newDataArr);
}
The echo I get is the following:
[{"ID->id":"esKZSCDfIC"},{"DT->createdAt":"2020-01-26T13:02:42"},{"DT->updatedAt":"2020-01-26T13:02:42"},{"ST->aString":"hey1"},{"NU->number":123},{"GPS->coords":["2.2222","44.4444"]},{"BL->aBool":false},{"AR->theArray":["xx","ww"]},{"FL->theFile":"https:\/\/xscoder.com\/xserver\/uploads\/6dydDtoTt5JjZzFc5L5V_image.jpg"},{"PO->userPointer":"vbN3b0C7bC"}]
Then I'll have to add that array into my JSON file as it follows:
$data = json_encode(array_values($newDataArr), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents('Test.json', $data);
But of course the syntax of my $newDataArr is not the right one, each JSON object must not be inside the { }, so this:
{"ID->id":"esKZSCDfIC"},
must become:
"ID->id":"esKZSCDfIC",
Is there a way to dynamically create a valid JSON array and push it to my Test.json file?
I've been through many posts on StackOverflow, but the result I get is always the same. I must use the PHP code above to get keys and values from my HTML inputs.
Instead of creating and pushing a new array on each iteration, set the values this way:
$newDataArr[$k] = $_POST[$k];
Hope this helps.

How to properly convert string form post variables to objects or arrays [duplicate]

This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 3 years ago.
I have tried most of the solutions I found, but cannot get it to work.
I have a form parameter that post list of ids separated with commas in a string as per
$list_of_ids = "261,420,788";
Now I need to convert the list of ids into object or arrays so that I can loop through it and insert into database.
My problem is how I can make it look like this:
["261","420","788"]
Here is how I will like to loop it and update database
foreach($list as $id){
echo $id;
// loop and update database
}
$list = explode(",", $list_of_ids);
Should give you an array of the numbers. Take precaution against sql-injections though, if you want to put this into a database!
Just use explode :
$string= "123,234,345";
$array = explode(",",$string);
Output :
Array ( [0] => 123 [1] => 234 [2] => 345 )

PHP JSON Arrays within an Array

I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);

Storing mysqli_query into multidimensional php array and utilizing that array as input to highcharts

I have a question on saving mysqli_fetch_array into multidimensional php array,I have month and amount as data, ex January-12345.0987,February-87654.3456 etc, I am able to get the data from database and able to store it as two different arrays, but I would like to store it in single one and then I want to use that array to send input to highcharts. Can any one please suggest me, below is the code I used for storing the retrieved data into two different arrays
$month=array();
$amount=array();
$i=0;
while($user_data = mysqli_fetch_array($data))
{
//echo 'inside while loop';
$month[$i]=$user_data['month'];
$amount[$i]=$user_data['monthavg'];
$i++;
//$month[$i][$i]=$user_data['month']['monthavg'];
}
I should either use a two dimensional array (the boring way)
$records = mysqli_fetch_all($data);
// Access array of attributes of the first row
var_dump($records[0]);
// Access attribute 'month' of first row
var_dump($records[0]['month']);
// Access attribute 'monthavg' of first row
var_dump($records[0]['monthavg']);
or objects (the cool way):
$records = array();
while($record = mysqli_fetch_object($data))
{
$actualData[] = $record;
}
// Access array of attributes of the first row
var_dump($records[0]);
// Access attribute 'month' of first row
var_dump($records[0]->month);
// Access attribute 'month' of first row
var_dump($records[0]->monthavg);
Then write your JSON or CSV response for your highchart JavaScript app:
$out = fopen('php://output', 'w');
fputcsv($out, $records);
fclose($out);
I recommned you to prepare correct array structure in the php, then use json_encode(). In the javascript use $.getJSON() and load your data. As a result you avoid csv / loading files and parsing it again.

How to filter JSON array into PHP array

I have a JSONArray generated in java and I post it to one of my PHP files where it's saved to a file. From there it gets read and I need to generate a chart based on this data. All I need is to convert my raw JSON which has values I don't need, into a simply php array.
[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]
Is an example of 2 elements inside my JSON array. What I need todo is filter those values into arrays accordingly.
For example get how many votes a 'player' has, I need to add up how ever many elements are in the JSONArray, because 1 element is 1 vote (the id is primary auto-increment in my mysql DB, not located on my webserver)
I'd like the array to be to [player, votes] so when I echo the array it will be easily parsed by the google chart tools I'm using. I've spent the last 5 hours working on this and I've been stuck, thanks for any help!
To decode the JSON into a php array, you can do:
$json_array = json_decode($raw_json);
Then, to get the number of votes for each player out of the array:
$player_votes = array_reduce($json_array,
function($v, $item) {
if(!array_key_exists($item->player, $v))
$v[$item->player] = 1;
else
$v[$item->player] = 1 + $v[$item->player];
return $v;
}, array());
If I understand your question correctly, this will work.
EDIT: Updated the second code snippet
Try this :
$str = '[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]';
$res = array();
foreach(json_decode($str,true) as $val){
if(array_key_exists($val['player'],$res)){
$res[$val['player']] = $res[$val['player']]+1;
}
else{
$res[$val['player']] = 1;
}
}
echo "<pre>";
print_r($res);
Output :
Array
(
[Orangeguy24] => 2
)

Categories