I have a list of country names in an input field like:
Spain Italy France Germany
So first of i make all the strings lowercase in order not to have a mismatch with the country name in the geoJson data. Then I compare the strings with the propriety name in the geoJson, and if it matches, i push it in the array.
$json = file_get_contents("../world_ita.json");
$data = json_decode($json, true);
$states = array();
$item = null;
$stateList = strtolower( usp_get_meta(false, 'usp-custom-3'));
$stateList = htmlspecialchars_decode ( $stateList);
$stateList = preg_replace("/\w[\w']*/e", "ucwords('\\0')", $stateList);
$stateList = explode(' ',$stateList);
foreach($data["features"] as $feature) {
$id = $feature["id"];
$name = $feature["properties"]["name"];
$feature["properties"]["density"] = 0;
foreach($stateList as $state) {
if ($name == $state) {
if (!in_array($name, $states)) {
$item = $feature;
array_push($states, $name);
}
} else { ?>
statesData.features.forEach(function(state) {
if ("<?php echo $id;?>" == state.id) {
state.properties.density += 10;
}
});
<?php }
}
}
if (!is_null($item)) : ?>
statesData.features.push(<?php echo json_encode($item); ?>);
<?php endif; ?>
The above is not working and it breaks it. I thought to first explode the strings and then loop them and run the other bits of the code, I am not sure where I am doing something wrong there.
UPDATE
What the above code does is to repeat the following for each single object in the geoJson
statesData.features.forEach(function(state) {
and it is not printing the coordinates as it should as I run the following by the end of it:
if (!is_null($item)) : ?>
statesData.features.push(<?php echo json_encode($item); ?>);
<?php endif;
It is only printing one single country coordinates but the name are the same as per the geoJson, so it should print all matching ones.
UPDATE 2
The code I am trying out is exactly this (different from the previous as per the new update):
var statesData = {
"type": "FeatureCollection",
"features": []
};
<?php
$json = file_get_contents("http://www.jikupin.com/world_ita.json");
$data = json_decode($json, true);
$states = array();
$classesForCountries = [];
$item = null;
$stateList = strtolower( usp_get_meta(false, 'usp-custom-3'));
$stateList = htmlspecialchars_decode ( $stateList);
$stateList = preg_replace("/\w[\w']*/e", "ucwords('\\0')", $stateList);
$stateList = explode(' ',$stateList);
foreach($data["features"] as $feature) {
$name = $feature["properties"]["name"];
foreach($stateList as $state) {
if ($name == $state) {
if (!in_array($name, $states)) {
$item = $feature;
array_push($states, $name);
}
}
}
}
if (!is_null($item)) : ?>
statesData.features.push(<?php echo json_encode($item); ?>);
<?php
endif;
?>
The above is not printing any coordinates, If I remove the explode and the loop I do for it, meaning if i run it for one single country, it works. When I run the explode and the loop for for that, and I try var_dumb($states), i get
value (0)
Related
I am trying to loop through a JSON Array returning a unique date and all the tasks associated with that date.
This is an example of my JSON array:
<!-- language: lang-json -->
[
{
"task":"Clean my teeth",
"date":"today"
},
{
"task":"Jumping Jacks",
"date":"tomorrow"
},
{
"task":"Call Mom",
"date":"today"
},
{
"task":"Wash The Dog",
"date":"2017/03/01"
},
{
"task":"Clean The House",
"date":"today"
}
]
I want to display something like this:
Today
Clean my teeth
Call Mom
Tomorrow
Jumping Jacks
2017/03/01
Clean The House
Here is my function: I can get all the unique days but I'm not sure how to display the tasks associated with that day.
public static function Iteration()
{
$file = file_get_contents("newfile.php");
$result = rtrim( $file, ",");
$array = json_decode('[' . $result . ']');
$unique_dates = array();
$unique_tasks = array();
foreach($array as $item) {
if ( in_array($item->date, $unique_dates) ) {
continue;
}
$unique_dates[] = $item->date;
$time = strtotime($item->date);
$newformat = date('Y-m-d',$time);
echo '<h2>' . $newformat . '</h2>';
echo $item->task;
}
}
You can traverse the JSON list, and keep the unique records and store tasks at the same traversal.
By using the isset(), you can determine whether the key is unique or not.
Try this:
<?php
$json = '[{"task": "Clean my teeth","date": "today"},{"task": "Jumping Jacks","date": "tomorrow"},{"task": "Call Mom","date": "today"},{"task": "Wash The Dog","date": "2017/03/01"},{"task": "Clean The House","date": "today"}]';
$array = json_decode($json);
$res = array();
foreach ($array as $each) {
if (isset($res[$each->date]))
array_push($res[$each->date], $each->task);
else
$res[$each->date] = array($each->task);
}
foreach ($res as $date => $tasks){
echo "<h3>{$date}</h3>";
foreach ($tasks as $task)
echo "<p>$task</p>";
}
<?php
{
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
?>
I get the same 20 results every time, and I have used pagination as you can see in my code. Every time I print the next page token I get a different one.
I would really appreciate if someone could point out the error in my code because I am stuck with this for quite some time. You are also most welcome to give any kind of relevant suggestion.
use pagetoken instead of nextpage in your url string and in the last two calls give only api key and page token as parameter and after each api call use sleep(2) i tried your code and it works perfectly when the following changes are made.happy coding!
<?php
//echo"hello";
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL ="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=26.177194999999998,91.77591333333334&radius=3000&types=mosque&key=your APIkey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
foreach( $dataArray->results as $details) {
//echo $details->place_id;
array_push($references, $details->place_id);
}
foreach($references as $reference)
{
$count=$count+1;
//echo $count." ";
$placeSearchURL="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$reference."&key=your apikey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
echo $dataArray->result->name."<br>";
echo "lat ".$dataArray->result->geometry->location->lat."<br>";
echo "lon ".$dataArray->result->geometry->location->lng."<br>";
echo "address ".$dataArray->result->formatted_address."<br>";
echo "<br>";
}
?>
basically i wanted to find a way to get more than 20 places of type masjid so i first used radar search to get placeids and then for each placed_id got the information and best part is you can get arount 200 results of nearby places
Im parsing json with php in this simple piece of code
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
foreach($records as $record)
{
echo $record['number']." ".$record['opened_at'];
}
?>
But i want to echo how many 'number' element are in my json file exemple bellow
{
"records":[
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
$numberCount = 0;
foreach($records as $record)
{
$numberCount += isset($record['number']); // Here we go
echo $record['number']." ".$record['opened_at'];
}
echo $numberCount;
?>
This function might be helpful: http://www.php.net/manual/en/function.array-count-values.php
$counts = array_count_values($records);
$numberCount = $counts['number'];
I have a wallposts MySql table with a tag_filter field, this field will have a comma seperated value.
I want to get all the unique/distinct tags for a user from this tag_filter field and populate in ul element.
There could be many posts per user.
eg
post1: tag_filter = a, b, c
post2: tag_filter = a, d, e
post3: tag_filter = c, d, e
the desired output would be
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
Here is my code thus far:
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$list = "<ul>";
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
foreach( $info as $item ) {
$list.="<li>$item</li>\n";
}
}
$list .= "</ul>";
echo $list;
I would also like to populate a js var with the distinct/unique list acquired from the above.
var sampleTags = [
<?php
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$all_tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
$all_tags = array_merge($all_tags, $info);
}
$tags = array_unique($all_tags); // values will be sorted by the function
foreach( $tags as $item ) {
$list = "$item";
}
echo join(',', $list);
?>
];
This might help.
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$tags[] = explode(",", $value); // put all in an array
}
// now, join and remove duplicates and sort in ascending order
$tags = implode( ',', $tags );
$tags = explode( ',', $tags );
$tags = array_values( array_unique( $tags ) );
sort($tags);
$list = "<ul>";
foreach( $tags as $item ) {
$list .= "<li>$item</li>\n";
}
$list .= "</ul>";
echo $list;
Hope this helps.
Comma separated values in a MySQL field is a sign of a bad database design, linked tables should be used if possible.
However, in your case, the following code might work:
$all_tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
$all_tags = array_merge($all_tags, $info);
}
$tags = array_unique($all_tags); // values will be sorted by the function
foreach( $tags as $item ) {
$list .= "<li>$item</li>\n";
}
To put all tags in a javascript variable:
<script type="text/javascript">
var sampleTags = [<?php echo explode(', ', $tags); ?>];
</script>
Try merging all tag_filter arrays with array_merge() and then use array_unique() to remove duplicates.
Just try with the following example :
<?php
$post_array = array('a,b,c','a,d,e','c,d,e');
$tag_list = '<ul>';
$i=0;
while($i < count($post_array)){
$filter_explode = explode(',',$post_array[$i]);
$filter_count = count($filter_explode);
for($j=0;$j<$filter_count;$j++)
{
if(!in_array($filter_explode[$j],$tag_list_build)){
$tag_list_build[] = $filter_explode[$j];
}
}
$i++;
}
$tag_list_build_count = count($tag_list_build);
for($k=0;$k<$tag_list_build_count;$k++)
{
$tag_list.= '<li>'.$tag_list_build[$k].'</li>';
}
$tag_list.= '</ul>';
echo $tag_list;
?>
I think this may help you to resolve your problem.
I am querying a database for results and trying to convert them into JSON encodable array where the key will act as the name of the pair and the value is the value. How would I do this in the following code below?
foreach($results as $result) {
foreach( $result as $key => $value ) {
if ($key == 'D')
{
$trimmed = round($value, 4);
}
else
{
$trimmed = trim($value, "\n\r");
}
$array[$i] ="$key"."=>"."$trimmed";
}
$i = 0;
$jret = json_encode($array);
echo $jret;
}
For example:
<?php
$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
?>
output:
{"1": {"foo": "bar", "12": "true"}}
dunno what you need and why you mimic PHP code instead of using it, but may be
$array[] = array($key => $trimmed);
is what you are looking for
with
$array[$i][$key] = $trimmed;
you could do
$return = json_encode($object, JSON_FORCE_OBJECT);
at the end