Data from array into html combobox - php

I have 2 arrays inside the class Continente..both public and i populate the arrays with records from mysql database.
class Continente{
public $continente = array();
public $tari= array();
}
And i have an object for wich i call the methods to put data into my arrays.
$cont = new Continente;
$cont->setContinente();
$cont->setTari();
Now the arrays look like this:
Array (
[0] => Array ( [Id] => 1 [Nume] => Europa )
[1] => Array ( [Id] => 2 [Nume] => Asia )
[2] => Array ( [Id] => 3 [Nume] => Africa ) )
and:
Array
( [0] => Array ( [Id] => 0 [Nume] => Romania [idContinent] => 1 [Populatie] => 2500 )
[1] => Array ( [Id] => 0 [Nume] => Bulgaria [idContinent] => 1 [Populatie] => 2200 )
[2] => Array ( [Id] => 0 [Nume] => Estonia [idContinent] => 1 [Populatie] => 1100 )
[3] => Array ( [Id] => 0 [Nume] => Japonia [idContinent] => 2 [Populatie] => 5000 )
[4] => Array ( [Id] => 0 [Nume] => China [idContinent] => 2 [Populatie] => 4599 )
[5] => Array ( [Id] => 0 [Nume] => India [idContinent] => 2 [Populatie] => 6000 )
[6] => Array ( [Id] => 0 [Nume] => Egipt [idContinent] => 3 [Populatie] => 444 ) )
now i need to make a combox with the 3 continents , and for each continent selected i need to print the first 3 countries sorted by the bigest number in 'Populatie' .
So i can select the contries for the continents... i have Id=idContinent .
Now i really don't know how to do this. Write a method for this in php? As i already have the arrays... or html?
This is what i tried:
<html>
<head></head>
<body>
<div>
<br>
<select>
<?php
foreach($cont->tari as $val ){
echo '<option value="'.$val.'">'.$val.'</option>';
}
?>
</select>
</div>
</body>
</html>

If you can do it, I think you can clean up your data structure quite a bit and it would make it easier to accomplish what you are trying to do. If you store your information like this:
$data = array( Europa => array (Romania => 2500,
Bulgaria => 2200,
Estonia => 1100 ),
Asia => array ( Japonia => 5000,
China => 4599,
India => 6000 )
...);
Then you may be able to eliminate the need for your "ID" keys and just use the array indices for your IDs.
Then you can just sort your subarrays by value using arsort(). Something like this:
foreach( $data as $cont => $pop_data ) {
arsort( $pop_data );
}
Then for creating your combo boxes, use similar code:
foreach( $data as $cont => $pop_data ) {
echo $cont . " Population Info:" . "<br>"; // or whatever
foreach( $pop_data as $country => $pop ) {
echo '<option value="'.$pop.'">'.$pop.'</option>';
}
}

Related

PHP Get values from nested array

I am new to PHP and Arrays, I am trying to get the values from an array. But no matter how I'm trying to do it, I can't get the value. What am I doing wrong?
The Array:
Array ( [playerinfo] => Array ( [rank] => Godfather [cash] => € 8,520,530 [weapon] => M-16 (29000) [health] => Array ( [width] => 100 [color] => green ) [wealth] => Too rich to be true [protection] => Bulletproof Humvee [plf] => Huge [plane] => Concorde [crew] => None [pbf] => Large [ship] => None ) [character] => Array ( [crime] => Array ( [0] => 120 [1] => 69 ) [gta] => Array ( [0] => 400 [1] => 70 ) [drugs] => Array ( [0] => 120 [1] => 2528 ) [airport] => Array ( [0] => 2700 [1] => 2529 ) [oc] => Array ( [0] => 86400 [1] => 1442364 ) [tr] => Array ( [0] => 10800 [1] => 1640016011 ) [plf] => Array ( [0] => 7200 [1] => 6712 ) [kill] => Array ( [0] => 3600 [1] => 1640019611 ) ) )
The way I tried to get the info:
$AccData = json_decode($MobinfoString, true);
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['cash'].'<br/>';
foreach ($AccData as $playerinfo) {
echo $playerinfo['playerinfo']['rank'].'<br/>';
echo $playerinfo['character']['gta'].'<br/>';
}
EDIT:
The json string
{"playerinfo":{"rank":"Boss","cash":"€ 5,923,712","weapon":"M-16 (4500)","health":{"width":"100","color":"green"},"wealth":"Too rich to be true","protection":"Bulletproof Humvee","plf":"Huge","plane":"Concorde","crew":"None","pbf":"Large","ship":"None"},"character":{"crime":[120,122],"gta":[400,369],"drugs":[120,2582],"airport":[2700,2582],"oc":[86400,1640020450],"tr":[10800,1640016850],"plf":[7200,3935],"kill":[3600,1640020450]}}
Anyone knows how to do this ? For example I need the Concorde from plane in a variable and the time values from gta in a variable. And some more from this string.
So your first Part is okay and you rank you can just display like the first part as well
$AccData = json_decode($MobinfoString, true);
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['cash'].'<br/>';
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['plane'].'<br/>';
echo $AccData['character']['gta'][0].'<br/>';
but the character is on the same level as playerinfo so you need to access it from AccData. also gta is an array like health, so you have to specify which value you want to show, the first so 0 or second which is 1

Parse XML to Array with SimpleXML

I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].

Echo arrays in foreach loop codeigniter

I've been using codeigniter for years but there's a really big gap in between so i always find myself in situations where i forgot how to do things and its almost midnight here so my brain isn't working fast. Can someone show me how to echo the array i have and explain to me how they are processed in the foreach loops?
I have this code in my model to take the rows in 2 tables.
public function tag_genre(){
$result['tag'] = $this->db->get('tags')->result_array();
$result['genre'] = $this->db->get('genre')->result_array();
return $result;
}
And I have this in my controller
public function view_publish_story(){
$data = array('tag_genre' => $this->story_model->tag_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
I used print_r in my view and this is the result. Seeing this just confuses me more. It's been atleast 2 years since i even dealt with foreach loops.
Array ( [tag] => Array ( [0] => Array ( [tag_id] => 1 [tag_name] =>
LitRPG ) [1] => Array ( [tag_id] => 2 [tag_name] => Virtual Reality )
[2] => Array ( [tag_id] => 3 [tag_name] => Cyberpunk ) [3] => Array (
[tag_id] => 4 [tag_name] => Reincarnation ) [4] => Array ( [tag_id] =>
5 [tag_name] => Summoned Hero ) [5] => Array ( [tag_id] => 6
[tag_name] => Martial Arts ) [6] => Array ( [tag_id] => 7 [tag_name]
=> Slice of Life ) [7] => Array ( [tag_id] => 8 [tag_name] => Overpowered ) [8] => Array ( [tag_id] => 9 [tag_name] => Non-Human )
[9] => Array ( [tag_id] => 10 [tag_name] => Anti-hero ) ) [genre] =>
Array ( [0] => Array ( [genre_id] => 1 [genre_name] => action ) [1] =>
Array ( [genre_id] => 2 [genre_name] => adventure ) [2] => Array (
[genre_id] => 3 [genre_name] => comedy ) [3] => Array ( [genre_id] =>
4 [genre_name] => Drama ) [4] => Array ( [genre_id] => 5 [genre_name]
=> Fantasy ) [5] => Array ( [genre_id] => 6 [genre_name] => Historical ) [6] => Array ( [genre_id] => 7 [genre_name] => Horror ) [7] => Array
( [genre_id] => 8 [genre_name] => Psychological ) [8] => Array (
[genre_id] => 9 [genre_name] => Romance ) [9] => Array ( [genre_id] =>
10 [genre_name] => Sci-fi ) [10] => Array ( [genre_id] => 11
[genre_name] => Mystery ) [11] => Array ( [genre_id] => 12
[genre_name] => Tragedy ) [12] => Array ( [genre_id] => 13
[genre_name] => Short Story ) [13] => Array ( [genre_id] => 14
[genre_name] => Satire ) ) )
I've been looking at various questions regarding arrays from assoc to multidimensional and other stuff. Then i finally visited php manual for foreach loop and i finally was able to echo the array. The problem now is that although it echoes my array it also has an error for each, i can probably fix the error part by declaring it as a defined variable. My question is, is there any other better way? or any improvement on how i made my array to make it cleaner or easier to print?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo $values['tag_name'];
}
}
UPDATE: i changed the way i made the array.
This is now my model:
public function get_tags(){
$query = $this->db->get('tags')->result_array();
foreach($query as $row){
$result[$row['tag_id']] = $row['tag_name'];}
return $result;
}
public function get_genre(){
$query = $this->db->get('genre')->result_array();
foreach($query as $row){
$result[$row['genre_id']] = $row['genre_name'];}
return $result;
}
and my controller:
public function view_publish_story(){
$data = array('tag' => $this->story_model->get_tags(), 'genre' => $this->story_model->get_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
and in my view:
<tr>
<div class="form-group">
<td><label for="genre">Genre</label></td>
<?php
foreach($genre as $genre_id => $genre_name){
echo "<td><label class='checkbox-inline'><input type='checkbox' value=''>".$genre_name."</label><td>";
}
?>
</div>
</tr>
My problem now is that, how do i fit all these into my table? I just ruined my table right now since i echoed them all in a single line. How do i do it so that it is printed in 3 columns?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo '<pre>';
echo $values['tag_name'];
}
}
this will format your array in a way you can read it and understand it.

Multidimensional array - duplicate of values through iterations

I have started working with Magento, and I'm trying to get all custom options associated with a given product.
I've found a solution to that, however, I ran into issues.
My PHP-code:
foreach ($_product->getOptions() as $optionInfo) :
$values = $optionInfo->getValues();
foreach ($values as $values) :
$valuesArray[$values['option_type_id']] = array("option_type_id" => $values['option_type_id'], "option_id" => $values['option_id'], "title" => $values['title']);
endforeach;
$option = array("id" => $optionInfo->getId(), "type" => $optionInfo->getType(), "title" => $optionInfo->getTitle(), "values" => $valuesArray);
$options[$optionInfo->getId()]= $option;
endforeach;
It sure do return the correct information. Atleast in the first iteration:
[2] => Array
(
[id] => 2
[type] => drop_down
[title] => Custom option 1
[values] => Array
(
[4] => Array
(
[option_type_id] => 4
[option_id] => 2
[title] => Flaphack 1
)
[5] => Array
(
[option_type_id] => 5
[option_id] => 2
[title] => Flaphack 2
)
[6] => Array
(
[option_type_id] => 6
[option_id] => 2
[title] => Flaphack 3
)
)
)
However, during the second iteration (and perhaps even the third and forth and so on), I'm having duplicates of the values. In the second iteration, I'm getting the same values as i got in the first iteration PLUS the correct values for the second iteration:
[1] => Array
(
[id] => 1
[type] => drop_down
[title] => Custom option 2
[values] => Array
(
[4] => Array
(
[option_type_id] => 4
[option_id] => 2
[title] => Flaphack 1
)
[5] => Array
(
[option_type_id] => 5
[option_id] => 2
[title] => Flaphack 2
)
[6] => Array
(
[option_type_id] => 6
[option_id] => 2
[title] => Flaphack 3
)
[1] => Array
(
[option_type_id] => 1
[option_id] => 1
[title] => Flaphack 1.1
)
[2] => Array
(
[option_type_id] => 2
[option_id] => 1
[title] => Flaphack 1.2
)
[3] => Array
(
[option_type_id] => 3
[option_id] => 1
[title] => Flaphack 1.3
)
)
)
Do you guys have any idea what's going on? Would be greatly appriciated.
Best,
Nikolaj
Try this code,
foreach ($_product->getOptions() as $optionInfo) :
$values = $optionInfo->getValues();
$valuesArray = array(); // added line
foreach ($values as $values) :
$valuesArray[$values['option_type_id']] = array("option_type_id" => $values['option_type_id'], "option_id" => $values['option_id'], "title" => $values['title']);
endforeach;
$option = array("id" => $optionInfo->getId(), "type" => $optionInfo->getType(), "title" => $optionInfo->getTitle(), "values" => $valuesArray);
$options[$optionInfo->getId()]= $option;
endforeach;
The $valuesArray is getting values in each iteration and you never cleared it. So when the outer foreach gets into second loop the $valuesArray gets values in incremental fashion. If you clear $valuesArray in each iteration of outer foreach you will get what you wanted.

Get value in mutli array

How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}

Categories