i need to create chart based on php array and i found something about traversing in stackoverflow posts but those answers doesnt help for converting this:
Array
(
[product sample 1] => Array
(
[0] => Array
(
[hitsTotal] => 63
)
[1] => Array
(
[hitsTotal] => 113
)
)
[product sample 2] => Array
(
[0] => Array
(
[hitsTotal] => 57
)
[1] => Array
(
[hitsTotal] => 107
)
)
)
to
['product sample 1', 63, 113],
['product sample 2', 57, 107]
how to convert?
Assuming $input is the array you present in your post you can do the following:
$output = array();
foreach($input as $key => $value)
{
$obj = array();
$obj[] = $key;
$obj[] = $value[0]['hitsTotal'];
$obj[] = $value[1]['hitsTotal'];
$output[] = $obj;
}
var_dump($output); //This will print it on screen so you can validate the output
To prepare your data for passing to js(client side) as an array of arrays use the following approach (array_walk, array_column, array_merge and json_encode functions):
// supposing that $arr is your initial array
$result = [];
array_walk($arr, function($v, $k) use(&$result){
$hitsTotals = array_column($v, 'hitsTotal');
$result[] = array_merge([$k], $hitsTotals);
});
echo json_encode($result);
The output:
[["product sample 1",63,113],["product sample 2",57,107]]
Related
This question already has answers here:
PHP json_decode integers and floats to string
(6 answers)
Closed 3 years ago.
I am trying to add multiple markers into a google map and i have found a way to do that here.
Now I have a json array response from the server as shown below.
// function to get user names and addresses
public function getUserAddresses(Request $request)
{
$users = User::where('address', '!=', null)->select('name', 'address')->get(); //this is a laravel query
$userData = [];
foreach ($users as $user) {
$userData[$user->name] = $user->address;
}
return $userData;
}
This code above is what gives me the response below.
{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}
but for me to use this data it must be in these format as shown below in javascript.
[
["plumber1", -1.2523238641713191,36.87899683074249],
["plumber2", -1.2192245641713191,36.87899687428849],
["allan plumber", -1.2192238641713191,36.87899683068849]
];
You can use this php code
$str = '{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}';
$array =json_decode($str);
$new_array = [];
foreach ($array as $key => $value) {
$coordinates = explode(',',$value);
$coordinate1 = (float) $coordinates[0];
$coordinate2 = (float) $coordinates[1];
$new_array[] = array($key,$coordinate1,$coordinate2);
}
print_r($new_array);
OUTPUT
Array
(
[0] => Array
(
[0] => plumber1
[1] => -1.25232386
[2] => 36.878996830742
)
[1] => Array
(
[0] => plumber2
[1] => -1.2192245641713
[2] => 36.878996874288
)
[2] => Array
(
[0] => allan plumber
[1] => -1.2192238641713
[2] => 36.878996830688
)
)
You can also check the demo here
Here is Javascript version
<script type="text/javascript">
var str = `{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}`;
var obj = JSON.parse(str);
var array = [];
var counter =0;
for (var key in obj) {
var myarr = obj[key].split(",");
array[counter] = [key, parseFloat(myarr[0]), parseFloat(myarr[1])];
counter++
}
console.log(array);
</script>
Try json_decode
ini_set( 'precision', 17 );
$jsonToArray = json_decode($json, JSON_NUMERIC_CHECK);
I have a PHP array that looks like this:
([NAME] => Array ( [0] => 16 [1] => 12 [2] => 4 [3] => 0 ))
([NAME2] => Array ( [0] => 19 [1] => 19 [2] => 0 [3] => 0 ))
([NAME3] => Array ( [0] => 31 [1] => 29 [2] => 2 [3] => 0 ))
This array is generated by PHP by pulling data from a database.
(The array is much larger than this, but for simplicity, I only included 3 records)
I really need this data to be usable in a script that generates a bar graph. For now, I only need the name and the first record. So, for example, in PHP
<?=$array['NAME'][0]?>
<?=$array['NAME2'][0]?>
would echo the information I need from each, but I'm not sure how to put that into the format I need into javascript.
This is the javascript format that I need:
{ tech: 'NAME', value: $array['NAME'][0] },
{ tech: 'NAME2', value: $array['NAME2'][0] },
{ tech: 'NAME3', value: $array['NAME3'][0] },
{ tech: 'NAME4', value: $array['NAME4'][0] },
...etc
Some type of loop would be preferred because the names can vary.
If it was just PHP I could do it, but I'm not too fluent in Javascript.
Could someone help me come up with a solution?
The good news is that you don't have to know much javascript. Create your data structure as you want it in php, and then use json_encode: http://php.net/manual/en/function.json-encode.php
<?php
$for_chart = array();
foreach($names as $key => $name){
$obj = new stdClass;
$obj->tech = $key;
$obj->value = $name[0];
$for_chart[] = $obj;
}
?>
the result is:
[{"tech":"NAME","value":1},{"tech":"NAME2","value":5},{"tech":"NAME4","value":9}]
You can use it in your javascript like this:
<script>
var my_names = <?=json_encode($for_chart)?>;
alert(my_names[0].value); // alerts "1"
</script>
http://sandbox.onlinephpfunctions.com/code/2682f09fd5515b220402db9c600b70a0501a87d9
If you json_encode the array you have, it comes out to:
{"NAME1":[16,12,4,0],"NAME2":[19,19,0,0],"NAME3":[31,29,2,0]}
which will give you a javascript object to iterate:
If you have the json object in a variable called arrayData:
var gridData = [];
for (var name in arrayData) {
var rowObj = { tech: name, value: arrayData[name][0] };
gridData.append(rowObj);
}
At the end of that, you will have an array of objects that should be what you're looking for in gridData.
If you would echo it in the following format you can JSON to get the data:
[{tech: 'NAME', value: $array['NAME'][0]},{tech: 'NAME', value: $array['NAME'][0]}]
In your js you could do something like the following:
var names = $.getJSON('http://localhost/index.php?name', function(data) {});
This way you have an array in js.
To get the javascript code just iterate over the php array an echo the json records like you want:
<?= foreach($array as $key => $value){
echo "{ tech: '" .$key ."', value: '" .$value[0] ."'},";
}
?>
//Assuming this is your array
$getArray["NAME"] = array(16,12,4,0);
$getArray["NAME2"] = array(19,19,0,0);
$getArray["NAME3"] = array(31,29,2,0);
$newArray = array();
foreach($getArray as $indKey=>$indArrVal) {
$newArray[] = array("tech"=>$indKey, "value"=>$indArrVal[0]);
}
echo json_encode($newArray);
here it is, create a new array, with the required indexes and then stringify it using json_encode
I have this array value: print_r ($array); which contains 2 data (this is latt and long of my gmap project).
The array is from:
<?php
if(isset($_GET['q'])) {
$q = $_GET['q'];
}
$q = isset($_GET['q']) ? $_GET['q'] : '';
$array = array();
$nsUser="SELECT * FROM cliententry WHERE kampusterdekat=:q";
$uQuery = $mydb->prepare ($nsUser);
$uQuery->execute(array(':q' => $q));
while ($result = $uQuery->fetch(PDO::FETCH_ASSOC)) {
$id=$result['id'];
$googlemap=$result['googlemap'];
//echo $googlemap;
$array[] = $googlemap;
print_r ($array);
}
?>
When I echo, the result will be like this:
Array
(
[0] => -5.364000343425874, 105.24465411901474
)
Array
(
[0] => -5.364000343425874, 105.24465411901474
[1] => -5.362878747789552, 105.24150252342224
)
Point:
What I need is to make the result into this format:
var wwwsitus = [
['<h4>area</h4>', wwwsitus[0]],
['<h4>area</h4>', wwwsitus[1]],
];
where locations (<h4>area</h4>) are removed. So, it must be, as follows:
var wwwsitus = [
[...,...],
[...,....],
];
Note:
Since I've no capable about array in JS, please help me to fix my title based on my issue. Thks in adv.
I'm loosing hairs on this.
I have an PHP array:
Array
(
[10-10-2015] => Array
(
[0] => Array
(
[hour] => 10:00
[title] => Meeting x
)
)
[10-09-2015] => Array
(
[0] => Array
(
[hour] => 17:00
[title] => another meeting
)
[1] => Array
(
[hour] => 11:11
[title] => other meeting
)
)
)
As you can see, there are two meetings in the same day.
That's correct.
I need to generate Javascript array:
var codropsEvents = {
'10-16-2015': ['<span>event one</span>', '<span>event two</span>'],
'10-17-2015': ['<span>event one</span>', '<span>event two</span>'],
};
Any help or suggestions how to do it ?
Use json.
echo 'var myJsArray = JSON.parse("'.json_encode($myPhpArray).'");';
You can use json_encode($array) in php to convert it to valid json string. In your javascript you can use JSON.parse(json) for parsing json string.
For example :
<?php
$array=array
(
'10-10-2015' => array
(
0 => array
(
'hour' => '10:00',
'title' => 'Meeting x'
)
)
);
?>
<script>
var data = JSON.parse('<?php echo json_encode($array); ?>');
// or var data = <?php echo json_encode($array); ?>;
</script>
Try this approach:
create array that You want:
<?php
$events = .....;
$data = [];
foreach($events AS $date => $eventsByDate) {
$data[$date] = [];
foreach($eventsByDate AS $event) {
$data[$date][] = '<span>'.$event['title'].'</span>';
}
}
?>
output $data array encoded as json string and parse it to get javascript object or array:
<script>
var codropsEvents = JSON.parse('<?=json_encode($data)?>');
console.log(codropsEvents);
</script>
New progress...
Without JSON.parse, only just:
var codropsEvents = <?=json_encode($events);?>
it's returning
var codropsEvents = {
"10-10-2015":[
{"time":"10:00","title":"Meeting X"}
],
"10-09-2015":[
{"time":"17:00","title":"Other event"},
{"time":"11:11","title":"Other Meeting"}
]
}
which causes returning Object
Any ideas ?
i have some problems with CSV files.
I have about 50 csv files, all looks the same like this below.
I need to import them into Php array - (later i put them into js var, and use in diagrams)
But the CSV dont looks like should do (i cant change it) - It have some data at top (first 10 lines) - i need to use them in different places (just show them - like "Kategoria:";"ROLNICTWO, LEŚNICTWO I ŁOWIECTWO"; - is a title)
"Okres sprawozdawczy:";"Dane roczne";
"Kategoria:";"ROLNICTWO, LEŚNICTWO I ŁOWIECTWO";
"Grupa:";"SKUP PRODUKTÓW ROLNYCH";
"Podgrupa:";"Skup produktów na 1 ha użytków rolnych";
"Wymiary:";"Wykaz produktów, Lata";
"Kod";"Jednostka terytorialna";"buraki cukrowe";"buraki cukrowe";"buraki cukrowe";"buraki cukrowe";
"2010";"2011";"2012";"2013";
"[kg]";"[kg]";"[kg]";"[kg]";
"1100000000";" ŁÓDZKIE";"278";"355";"363";"333";
"1140000000";" MAZOWIECKIE";"247";"250";"286";"348";
"2120000000";" MAŁOPOLSKIE";"67";"87";"114";"127";
"2240000000";" ŚLĄSKIE";"168";"218";"245";"281";
"3060000000";" LUBELSKIE";"1139";"1170";"1235";"1346";
"3180000000";" PODKARPACKIE";"249";"208";"342";"404";
"3200000000";" PODLASKIE";"6";"30";"5";"0";
"3260000000";" ŚWIĘTOKRZYSKIE";"479";"482";"337";"534";
"4080000000";" LUBUSKIE";"184";"141";"264";"229";
"4300000000";" WIELKOPOLSKIE";"1102";"1412";"1485";"1532";
"4320000000";" ZACHODNIOPOMORSKIE";"522";"830";"909";"642";
"5020000000";" DOLNOŚLĄSKIE";"1044";"1045";"1274";"1136";
"5160000000";" OPOLSKIE";"1392";"1386";"2113";"1660";
"6040000000";" KUJAWSKO-POMORSKIE";"1588";"2040";"2272";"2252";
"6220000000";" POMORSKIE";"624";"748";"724";"879";
"6280000000";" WARMIŃSKO-MAZURSKIE";"153";"150";"163";"167";
How i can print them as array - to looks like this:
[0] => Array
(
[0] Okres sprawozdawczy
[1] Dane roczne
)
[1] => Array
(
[0] Kategoria
[1] ROLNICTWO, LEŚNICTWO I ŁOWIECTWO
)
[2] => Array
(
[0] Grupa:
[1] SKUP PRODUKTÓW ROLNYCH
)
etc. first 5 lines of CSV lines.
But later from line 7 (6 is empty) - line 7,8,9 is one header..
"Kod" - its "1100000000"
"Jednostka terytorialna" - its "ŁÓDZKIE"
"buraki cukrowe","2010","[kg]" - "278"
"buraki cukrowe","2011","[kg]" - "355"
"buraki cukrowe","2012","[kg]" - "363"
"buraki cukrowe","2013","[kg]" - "333"
3 headers for one data, so i need i think something like that:
[6] => Array ([0] buraki cukrowe => Array ([0] 2010 => Array ([0] kg => Array ([0] 278)
Where the "278" is data what i need to use and put in to JS VAR.
Im not sure its good way to do this, please help me out..
First you set this file on variable, you can use file_get_content() like this
$csvData = file_get_contents('your_file.csv');
you can do it for all the files you need to add
After you have your $csvData you just have to explode and chunk it like this
$explodedCsvData = explode(';',$csvData);
$chuckedCsvData = array_chunk($explodedCsvData,2);
Something like that could do the trick :
$file = fopen('your-file.csv');
$header = true;
$headers = [];
$data = [];
while($line = fread($file)) {
if($line === '') { // Transition from headers to columns info
$header = false;
$line = fread($file);
$label = explode(';', $line);
$l = count($label);
$year = array_pad(explode(';', fread($file)), -$l, null);
$unit = array_pad(explode(';', fread($file)), -$l, null);
$column = [];
for($i=0; $i<$l; ++$i) {
$column[] = [
'label' => $label[$i],
'year' => $year[$i],
'unit' => $unit[$i]
];
}
}
elseif($header) { // Still in the first lines
$headers[] = explode(';', $line);
}
else { // After the columns parsing
$data[] = explode(';', $line);
}
}
fclose($file);