Looping through multiple arrays and display select options - php

I have a multi-select box for country selection. I want to select any countries which are associated, meaning an array I get from the database.
Here's the code I have:
<?php
foreach($countries as $country){
if(!empty($offer_countries)){
foreach($offer_countries as $key => $offer_country){
if(isset($offer_country['country_id']) && ($offer_country['country_id'] == $country['id'])){
echo '<option value="'.$country['id'].'" selected>'.$country['name'].'</option>';
}else{
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}
}else{
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}
?>
The $offer_countries array, looks like this:
Array
(
[0] => Array
(
[country_id] => 1
)
[1] => Array
(
[country_id] => 2
)
[2] => Array
(
[country_id] => 3
)
)
I'm looping all countries to display them, then I have a nested foreach to see if the country is already set, if so, make the option box selected.
The problem with this is that let's say I have 3 items selected, it'll display 3 of the same country, based on the number of items in the array. So if United States should be checked, it'll show it three times, with the last one checked.
Ok, sorry for the looong explanation, it's probably fairly self explanatory, but any help would be awesome!

This solved it:
<?php
foreach($countries as $country){
$i = 0;
if(!empty($offer_countries)){
foreach($offer_countries as $key => $offer_country){
if($offer_country['country_id'] == $country['id']){
echo '<option value="'.$country['id'].'" selected>'.$country['name'].'</option>';
$i = 1;
break;
}
}
if($i == 0){
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}else{
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}
?>

Your inner 'foreach' statement is going to output 'something' whether or not the value is set, and it does so based on the $country variable set up in the outer foreach loop.
So what happens is that you output on the outer 'foreach' loop once for each time it runs on the inner foreach loop.

Related

PHP- Finding the Sum of values for each ID in an Associative Array

I have 2 Arrays. The First Array is a 1D Array which contains User ID's.
Something like this Array ( [0] => 1042800 [2] => 1184921 [4] => 724911 [66] => 1271106 )
I have a second Array which is an Associative Array, which contains Information for each User ID. It is something like this
Harvest_DayEntry::__set_state(array('user-id'=>1042800 'hours'=>2 ,Harvest_DayEntry::__set_state(array('user-id'=>1042800 'hours'=>4 ))
That was actually a part of the array. Now I am Interested in calculating the total hours for each User ID.
This is what I have tried.
//Add all the Hours for a Given User ID
//$output is the Array of User ID's
$resultGetEntries=$api->getProjectEntries($project_id,$range);
$dayEntries= $resultGetEntries->data;
$i=0;
$sum=$sum[20];
$sum= array_fill(0, 20, 0);
foreach ($dayEntries as $key => $value) {
if($output[i] == $value->get("user-id")) {
$sum[$i] = $sum[$i] + $value->get("hours");
}
$i++;
}
Eventually I want to get something like this
User ID Hours
1042800 15
1184921 18
724911 10
1271106 8
I am not too sure how to go about it. I can't seem to figure out how do I loop over an Associative array and calculate the sum for each user ID at the same time. I just need to know the proper logic to solve this problem.
I assume $resultGetEntries is your user ids array and $dayEntries is the Harvest_DayEntrys array.
The simplest way to combine both is iterarting over both in a double loop:
$resultGetEntries = $api->getProjectEntries($project_id,$range);
$dayEntries = $resultGetEntries->data;
$sums = array();
foreach ($resultGetEntries as $i => $userId) {
$sums[$userId] = 0;
foreach ($dayEntries as $j => $dayEntry) {
if ($dayEntry->get("user-id") == $userId) {
$sums[$userId] += $dayEntry->get("hours");
}
}
}
print_r($sums);

php foreach to print multidimensional array into table?

So, I am sending a query based on a POST input that takes in numerous options, and want to print out one table PER selected option. I implode the array and it is correctly displaying the data, however it's all lumped up into one table where I need it separated. This is an example of my array now:
Array
(
[Selected Option 1] => Array
(
[Item 1] => Array
(
[Item 1 Data 1] => etc
[Item 1 Data 2] => etc
[Item 1 Data 3] => etc
)
)
And basically I need the table to be like Table 1: Selected Option 1 displaying all items and their data, followed by Table 2: Selected Option 2, and so on.
How is something like this done? When I do the foreach loop, it successfully prints out the header to each table (Selected Option 1, etc) but Im not sure how to filter it so only the correct data is printed instead of the ENTIRE array.
Thanks!
So far, this is what my foreach looks like
foreach ($selected_opt as $port=> $item) {
foreach ($item as $itemx => $data){
$var1= $data['1'];
$var2= $data['2'];
$var3= $data['3'];
You can use foreach inside foreach
let say your array is = $data
<?php
foreach ($data as $selectedOption => $items) {
echo $selectedOption . "<br>";
foreach ($items as $itemName => $itemData) {
echo $itemName . "<br>";
foreach ($itemData as $item) {
echo $item . "<br>";
}
}
}
?>
If you want to filter
echo $data["Selected Option 1"]["Item 1"]

Compare a String to the ID of a array?

So I'm trying to find the details for a particular item in one array from a different array:
foreach($json_items['result']['items'] as $item)
{
foreach($items_all['items_game']['items'] as $schemaItem)
{
echo $Schema[$item['defindex']];
if($item['defindex'] == $Schema[$item['defindex']])
{
echo "works";
echo $schemaItem['name'].'<br />';
break;
} else {
//echo "not";
}
}
}
defindex is a unqiue ID for the item, Schema is a database type array of item info
but Schema is designed like this:
[1] => Array
(
[name] => Anti-Mage's Glaive
[prefab] => default_item
So 1 here would be the defindex for this item in the Schema array
What can I do so can compare them and get out the info such as name and prefab for the item? Thanks.
Is this inside of a loop through the array? If so, you could try:
foreach ($item as $key => $value){
// Do compare here, $key would be the array index $value the value.
}
You could access the array in $Schema
$item = $Schema[$item['defindex']];
$item_name = $item['name'];
$item_prefab = $item['prefab'];

Assigning 'selected' to options of multiple select element

I have a comma separated list stored in mysql(I used implode after selections were made and stored this comma separated list). My problem is now applying 'selected="selected"' to each option that represents a previous choice when my page is refreshed. I have used a while loop to create the select box. I tried using a foreach loop inside of my while loop to check whether or not the 'while' value was in the 'exploded' previous selections. It only gave the value of 'selected' to the last item in my exploded list. Can anyone shed light on how to solve this problem? I think I am misunderstanding foreach and possibly the explode function.
Lets say your previous selected items are in a variable $selected, and your while looks as follows:
$selected = array('one', 'two');
while(//your fech or something i presume storing it in $row) {
$isSelected = in_array($row['value'],$selected) ? "selected='selected'" : "";
echo "<option {$isSelected} value='{$row['value']}'>{$row['name']}</option>";
}
my code, it´s not perfect but works!:
$var_options = array ( 1 =>
array ('name' => "None", 'varid' => "0"),
array ('name' => "Cars", 'varid' => "1"),
array ('name' => "Motos", 'varid' => "2"),
array ('name' => "Trucks", 'varid' => "3"),
);
$mysqlvalue = "2,3"
$mysqlvalue= explode(",",$mysqlvalue);
echo '<select name="vehicles[]" multiple size="6">'."\n";
foreach ($var_options as $arraydes) {
$idvariable = $arraydes[varid];
$namevariable = $arraydes[name];
$isSelected = in_array($idvariable,$mysqlvalue) ? "selected='selected'" : "";
if($isSelected != ""){
echo "<option {$isSelected} value='{$idvariable}'>{$namevariable} (SELECTED)</option>\n";
} else {
echo "<option value='{$idvariable}'>{$namevariable}</option>\n";
}
}
echo "</select>\n";
and to save to mysql:
$vehicles= implode(', ', $_POST['vehicles']);

php get the text into an array list

I have an array in the database. When I used print_r($variable_name), I got the array like this
Array
(
[0] => Array
(
[attribute_name] => Disk space,Color,Processor
)
)
So to get the value of attribute_name I tried this
foreach($attributes_name as $key=>$val) {
echo $val['attribute_name'];
}
Here I got the result like Disk space,Color,Processor. But I want the result should come like a list
<li>Disk Space</li>
<li>Color</li>
<li>Processor</li>
So can someone tell me how to do this?
Try this :
<?php
$arr = array(array("attribute_name" => "Disk space,Color,Processor"));
foreach($arr as $val) {
$resultArr = explode(",",$val['attribute_name']);
foreach($resultArr as $value){
echo "<li>".$value."</li>";
// Add id in li
echo "<li id='".str_replace(" ","_", strtolower($value))."'>".$value."</li>";
}
}
?>

Categories