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);
Related
My Jquery code
var attrid = [];
var attrvalue = [];
$.each($(".attname1"), function(index){
if($('.getval'+index+'').val() != undefined){
attrid.push($('.getval'+index+'').attr("id"));
attrvalue.push($('.getval'+index+'').val());
}
});
//outcome data
["5931", "5950", "5951", "5952"] //id
["cas", "bsd", "Canvas", "Grey"] //name
The result format that I actually want:
$ary = array (
[0] => array(
Id => 5931,
value=> cas,
),
[1] => array(
Id => 5950,
value=> bsd,
),
[2] => array(
Id => 5951,
value=> Canvas,
),
[3] => array(
Id => 5952,
value=> Grey,
)
);
Question:
Above code are using Jquery to loop the data and store into array, I'm trying to create loop to create the result format the I want, but I failed to do that,anyone can provide me some sample code or idea which is can using Jquery to create the results format that I provided.Thank you.
Make one array and push objects onto it:
var ary = [];
$('.attname1').each(function(index) {
var getval = $('.getval' + index);
if (getval.val()) {
ary.push({
id: getval.attr('id'),
value: getval.val()
});
}
});
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]]
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);