How to pass values with php from function into an array - php

I've read the Q&A regarding this topic, but it unfortunately doesn't answer my question, because I'm a Beginner in PHP.
I'm using a function to display a polygon on a google Map. That works all fine. The coords are stored in the following variable:
$polygon = array(
"43.231297 -79.813721",
"43.238438 -79.810768",
"43.230335 -79.809395",
"43.230312 -79.809296",
"43.240208 -79.808983",
"43.230225 -79.808884",
"43.240116 -79.808617",
"43.229823 -79.807388",
"43.231235 -79.802649",
"43.237137 -79.800774",
"43.231297 -79.813721"
);
I now want to get the latitude and longitude dynamically out of a MySQL database. My code below runs great and returns the desired coordinates:
<?
foreach ($BusinessAreaMunich as $item) {
echo "new google.maps.LatLng(" .$item['AreaCoordLatitude'] . "," .$item['AreaCoordLongitude'] . "), \n";
}
?>
However, I've tried to do the following:
$polygon = array(
foreach ($BusinessAreaMunich as $item) {
echo $item['AreaCoordLatitude'], $item['AreaCoordLongitude'];
}
);
Now I know that doesn't work, but I don't know how to solve my issue. Could you please give me an idea how to solve this?

Proper code is:
$polygon = array(); // define `$polygon` as array
foreach ($BusinessAreaMunich as $item) {
// create `string` value as a result of concatenating coords and a space
$coords = $item['AreaCoordLatitude'] . ' ' . $item['AreaCoordLongitude'];
// append a `string` to `$polygon`
$polygon[] = $coords;
// or simply:
// $polygon[] = $item['AreaCoordLatitude'] . ' ' . $item['AreaCoordLongitude'];
}
// output to see what you have
print_r($polygon);

Related

How do I get this php foreach to parse through all of the <mod> entries?

I need to parse the "name" and "version" attributes from all of the "<mod>" tag entries.
Thanks to this page I was only able to parse the first "<mod>" tag from the xml.
I'm no programmer, so I have no clue how to go on.
This is my xml file.
These are my testing php files.
$xmlfile = simplexml_load_file("packa.xml");
foreach ($xmlfile->children() as $mods) {
echo $mods->mod['name']."</br>";
echo $mods->mod['version'];
}
had this output.
</br></br>Just Enough Items</br>4.15.0.293
And
foreach ($xmlfile->children() as $mods) {
echo $mods->mod['name']."
</br>".$mods->mod['version'];
}
had this output
</br>
</br>Just Enough Items
</br>4.15.0.293
You can try something along these lines, using xpath:
$result = $xmlfile->xpath('//mods//mod');
foreach($result as $mod){
$nam = $mod->xpath('.//#name');
$ver = $mod->xpath('.//#version');
echo implode ( $nam). "</br>" .implode( $ver );
echo "<br>";
}
Output:
Just Enough Items
4.15.0.293
MTLib
3.0.6
CraftTweaker2
1.12-4.1.20
Mod Tweaker
4.0.18
etc.
You are using the wrong level in the XML in the foreach() loop, this is only looping over the <mods> elements - and there is only 1. You need to specify that you want to loop over the <mod> elements and then just access the attributes as you already do...
foreach ($xmlfile->mods->mod as $mod) {
echo $mod['name'] . "/" . $mod['version'] . "</br>" . PHP_EOL;
}

I want to show all result from an api

I'm working with google places API , and i showed content from the api but one by one like this
<?php
$str = file_get_contents('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=48.075971700000004,-0.7651981999999999&radius=5000&type=restaurant&keyword=cruise&key=AIzaSyDxXV4Ka8yiDq1-UKzlzX-MUC8csfdN8y4');
$maps_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=48.075971700000004,-0.7651981999999999&radius=5000&type=restaurant&keyword=cruise&key=AIzaSyDxXV4Ka8yiDq1-UKzlzX-MUC8csfdN8y4';
$maps_json = file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][1]['name'];
$lat2 = $maps_array['results'][2]['name'];
echo $lat;
echo "<br>";
echo $lat2;
?>
but i want to show all the result one time with a loop
Try
foreach ($maps_array['results'] as $map) {
echo $map['name'];
echo "<br>";
}
Put the results array in a foreach and make a loop from that. in that way u will get all the data instead of taking it 1 by 1. And for the numbers array u can add a ++ statement(not needed).
hope this helps. Good luck

Parsing XML Attributes by name with PHP5

When trying to parse an XML document in PHP, nothing is returned.
The XML document im trying to use:
http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml
The code I have tried:
$player = simplexml_load_file('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
foreach ($player->PlayerName as $playerInfo) {
echo $playerInfo['firstName'];
}
I have also tried:
$player = simplexml_load_file('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
echo "Name: " . $player->PlayerName[0]['firstName'];
What do I need to change for the attributes to show?
You might try to print_r the whole data youself and finally find what you need:
var_dump($player->Player->PlayerName->Attrib['value']->__toString())
//⇒ string(7) "Daniele"
To list all "values" (firstname, lastname,...) you need list all children and their attributes:
$xml = simplexml_load_file('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
foreach ($xml as $player) {
foreach ($player->PlayerName->children() as $attrib) {
echo $attrib['name'] . ': ' . $attrib['value'] . PHP_EOL;
}
}
Output:
firstName: Daniele
lastName: Viola
commonName: Viola D.
commentaryName:
This does not work, since you are trying to access an attribute and not a node value.
You might also run into problems, because the xml is not "valid" for simple xml. See my blogpost about the issues with parsing xml with php here http://dracoblue.net/dev/gotchas-when-parsing-xml-html-with-php/
If you use my Craur ( https://github.com/DracoBlue/Craur ) library instead, it will look like this:
$xml_string = file_get_contents('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
$craur = Craur::createFromXml($xml_string);
echo $craur->get('Player.PlayerName.Attrib#value'); // works since the first attrib entry is the name
If you want to be sure about the attribute (or select another one) use:
$xml_string = file_get_contents('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
$craur = Craur::createFromXml($xml_string);
foreach ($craur->get('Player.PlayerName.Attrib[]') as $attribute)
{
if ($attribute->get('#name') == 'firstName')
{
echo $attribute->get('#value');
}
}

Better way to parse XML using PHP to create hierarchy with data table in it

I recently (2 weeks ago) started coding in PHP and today I ran into a problem and wondering if somebody can help/guide me.
I am getting xml data from a Web Service and want to render the data as show in below image
The fetched XML looks like this
<pricesheets>
<pricesheet>
<buyinggroupname>China</buyinggroupname>
<categoryname>Category B</categoryname>
<currency>USD</currency>
<discamt>39330.00</discamt>
<productdesc>Product B description</productdesc>
<prdouctId> Product B </productId>
</pricesheet>
<pricesheet>
<buyinggroupname>Asia</buyinggroupname>
<categoryname>Category A</categoryname>
<currency>USD</currency>
<discamt>39330.00</discamt>
<productdesc>Product A description</productdesc>
<prodouctId> Product A </productId>
</pricesheet>
</pricesheets>
The issue I am having is what's the best way to parse above XML so that I can render products based on 'buyinggroupname' and 'categoryname'. I can easily accomplish the collapse and expand feature once I know how to render the data.
Below is what I have done to achieve what I want. But I know for sure that my code is NOT efficient and scalable.
$xmldata; // XML return by the webservice
$data = simplexml_load_string($xmldata);
$category_A_items = '';
$category_B_items = '';
foreach ($data as $object) {
if($object->categoryname == 'Category A') { // Bad Idea : Hard coded category
$category_A_items .= '<tr><td>'.$object->prdouctId.'</td><td>'. $object->productdesc. '</td><td>'. $object->discamt. '</td></tr>';
}
elseif($object->CATEGORYNAME == 'Category B') { // Bad Idea : Hard coded category
$category_B_items .='<tr><td>'.$object->prdouctId. '</td><td>'. $object->productdesc. '</td><td>'. $object->discamt. '</td></tr>';
}
}
//Render Category A items in table
if(strlen($category_A_items) > 0) {
echo '<h3>CAD</h3>';
echo '<table><tr><th>Product Name</th><th>Description</th><th>Price</th></tr>';
echo $cadItems;
echo '</table>'. PHP_EOL;
}
//Render Category B items in table
if(strlen($category_B_items) > 0) {
echo '<h3>Breast Biopsy</h3>';
echo '<table><tr><th>Product Name</th><th>Description</th><th>Price</th></tr>';
echo $breastBiopsy;
echo '</table>'. PHP_EOL;
}
The above code only renders the data based on categories ( which are hard coded). Now what would be better way of doing the same so that I can render the data based on 'buyingroupname' and 'categoryname' without hard coding either of this two values in the php code.
Thanks in advance!
get an array of unique <categoryname>-nodes with xpath, then loop through it and select all <pricesheet>-nodes with that specific category, letting xpath do that job, again:
$xml = simplexml_load_string($x);
$cat = array_unique($xml->xpath("//categoryname"));
foreach ($cat as $c) {
echo "$c<br />";
foreach ($xml->xpath("//pricesheet[categoryname='$c']") as $p) {
echo $p->productId."<br />";
}
}
see a live-demo # http://codepad.viper-7.com/m9ruRU
Of course, you have to add code for creating tables...
Putting the strings in arrays with variable keys lets PHP keep them organized for you, and you don't have to know any category names at all. I used multidimensional arrays so that each buyingroup has its categories inside it. Then you loop through the arrays to make each table. Let me know if you need more explanation. I misunderstood your image the first time I saw it.
$xmldata; // XML return by the webservice
$data = simplexml_load_string($xmldata);
$buyinggroups = array();
foreach ($data as $object) {
if(isset($object->buyinggroupname) || isset($object->BUYINGGROUPNAME)) {
if(isset($object->buyinggroupname)) {
$name = $object->buyinggroupname;
} else {
$name = $object->BUYINGGROUPNAME;
}
}
if(isset($object->categoryname) || isset($object->CATEGORYNAME)) {
if(isset($object->categoryname)) {
$category = $object->categoryname;
} else {
$category = $object->CATEGORYNAME;
}
}
if(isset($category) && isset($name)) { //just making sure this row is OK
if(!isset($buyinggroups[$name])) {
$buyinggroups[$name] = array(); //initialize the outer array
}
if(!isset($buyinggroups[$name][$category])) {
$buyinggroups[$name][$category] = ''; //this is like your previous $category_A_items
}
$buyinggroups[$name][$category] .= '<tr><td>'.$object->productId.'</td><td>'. $object->productdesc. '</td><td>'. $object->discamt. '</td></tr>';
}
}
//Render all categories in lots of tables
//I am guessing at what HTML you want here; I don't think it's necessarily correct
echo '<table>'. PHP_EOL;
foreach($buyinggroups as $name=>$set) {
echo '<tr><th colspan="2">'.$name.'</th></tr>'. PHP_EOL;
echo '<tr><th> </th><td>';
foreach($set as $category=>$rows) {
echo '<table>';
echo '<tr><th><h3>'.$category.'</h3></th>'. PHP_EOL;
echo '<td><table><tr><th>Product Name</th><th>Description</th><th>Price</th></tr>';
echo $rows;
echo '</table>'. PHP_EOL;
}
echo '</td></tr>';
}
echo '</table>';
EDIT:
This can't possibly be beyond your ability to debug. You are getting everything you need in order to debug. PHP tells you the line number and the error. You google the error and find out what it means. Then you go to that line number and see how what's there corresponds to the thing you googled. In this case, I can tell you that "illegal offset type" means that you have an array key that is not a string or integer. On those lines in the error messages, you have the array keys $name and $category. Try var_dump($name) and var_dump($category) to find out what they actually are, or even var_dump($object) to find out how to get name and category out of the object.

Send MultipleIterator to an email

my english may be confusing, i'll try to be specific. It's about PHP, here in stackoverflow i found a piece of code that is so near to give me what i want (an answer of ValkerK), i have two arrays to iterate into one and i found an answer to a question that was exactly what i was lookin for. I just need to create a variable and send the prints to an e-mail. It may be simpliest but i'm not exactly an expert, here is the code if you can help me, thanks for reading this.
$want = new ArrayIterator($_POST['product']);
$amount = new ArrayIterator($_POST['howmany']);
$it = new MultipleIterator;
$it->attachIterator($want);
$it->attachIterator($amount);
foreach($it as $e) {
echo $e[0], ' : ', $e[1], ", ";
}
Then i have this prints
Product1:10, Product2:12, Product3:7.... etc
I need a variable to send that to an e-mail, but i still can't make it it work... thankes for your help.
Use something like this:
$contents = '';
foreach($it as $e) {
$contents .= $e[0] . ' : ' . $e[1] . ", ";
}
Now you can email $contents, which will contain the exact same output. You can also use output buffering, but for such a simple use-case, I wouldn't bother with it.
$var = implode("\n",array_map(function($v){
return $v[0]. ':'. $v[1].",";
}, $it));

Categories