Add/get data to/from two Dimensional array Doesn't work - php

I'm trying to add data from database to 2-dimensional array and then unpacking.
This function is in a folder named imsConnection.php
function getCurrency() {
global $cn;
$sql = "select * from Currency";
$res = mysqli_query($cn, $sql);
$a = array();
if (mysqli_num_rows($res) > 0) {
while ($row = mysqli_fetch_array($res)) {
$a[] = array($row['currencyID'], $row['currencyName']);
}
}
return $a;
}
And to unpack it into drop box:
<select name="drpCurrency" required>
<?php
require_once("imsConnection.php");
$a = getCurrency();
foreach($a as $i) {
echo "<option value='$i'>$a[$i]</option>";
}
?>
</select>

To make a formal answer: If you create multi dimentaion array and you loop with foreach you need to echo the value according the key you need. In you case:
foreach($a as $i)
echo "<option value='" . $i["currencyID"] ."'>" . $i['currencyName'] . "</option>";
I recommend you change your array do be according key - change the getCurrency function as:
while($row = mysqli_fetch_array($res)){
$a[$row['currencyID']] = $row['currencyName'];
Then you can use it as:
$a = getCurrency();
foreach($a as $k => $i)
echo "<option value='$k'>$i/option>";
Assuming you want the value as currency ID and the option content as the currency name

Related

Print out something only when value is within specific group during loop in PHP

I have a big array that is being used throughout the site and changing its structure just for the following task would be a pain. I want to make several select boxes with another array. The output I want to get is like this:
/* Example Array:
$allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals",
"Crocodilians","Turtles");
$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
*/
<select name='Amphibian'>
<option value='0'>Frogs</option>
<option value='1'>Toads</option>
</select>
<select name='Mammal'>
<option value='2'>Bats</option>
<option value='3'>Elephants</option>
<option value='4'>Rats</option>
<option value='5'>Seals</option>
</select>
<select name='Reptile'>
<option value='6'>Crocodilians</option>
<option value='7'>Turtles</option>
</select>
I can't figure out how to print out the options only when the value is within the specific animal group during each iteration of $group. I have tried each() to get the next animal $endAnimal from $group and then break the internal loop if $animal matches the $endAnimal, but I also need to make the loop start printing options at specific values.
<?php
$allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals","Crocodilians","Turtles");
$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
foreach($group as $thisAnimal=>$category){
$nextKey = (each($group));
$endAnimal = $nextKey['key'];
print "<select name='$category'>";
foreach($allAnimals as $idx=>$animal){
print "<option value='$idx'>$animal</option>";
if($endAnimal === $animal){
break;
}
}
print "</select>";
}
?>
Please check this out:-
<?php
$allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals","Crocodilians","Turtles");
$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
$group_keys = array_keys($group); // get the keys of group array
$j = 0;
foreach($group_keys as $key => $group_k){
print "<select name='$group[$group_k]'>";
if(isset($group_keys[$key+1])){
$new_value = $group_keys[$key+1];
}else{
$new_value = '';
}
if($new_value ==''){
foreach($allAnimals as $key => $allAnm){
print "<option value='$j'>$allAnm</option>";
unset($allAnimals[$key]);
$j ++;
}
}else{
$key_from = array_search($new_value,$allAnimals);
for($i = 0; $i<$key_from; $i++){
print "<option value='$j'>$allAnimals[$i]</option>";
unset($allAnimals[$i]);
$j ++;
}
}
$allAnimals = array_values($allAnimals);
print "</select>";
}
Output:- https://eval.in/379462 (eval.in)
local end :- (for better showing) :- http://prntscr.com/7fmtbi
Array of Array is the solution I think
$group = array( "Amphibian" => array("Frogs", "Toads"), "Mammal" => array("Bats", "Elephants", "Rats", "Seals"), "Reptile" => array("Crocodilians", "Turtles") );
foreach($group as $thisAnimal=>$category){
print "<select name='$category'>";
foreach($category as $idx=>$animal){
print "<option value='$idx'>$animal</option>";
}
print "</select>";
}
Thank you for your responses and answers. I just sort of get that to work by checking whether $thisAnimal from $group is the same as $animal from $allAnimals during the internal loop. If it's the same, turn $passThis to true and then proceed to print out the option until $endAnimal matches $animal. Example
<?php
$allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals","Crocodilians","Turtles");
$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
foreach($group as $thisAnimal=>$category){
$nextKey = (each($group));
$passThis = false;
$endAnimal = $nextKey['key'];
print "<select name='$category'>";
foreach($allAnimals as $idx=>$animal){
if($animal === $thisAnimal){
$passThis = true;
}
if($endAnimal === $animal){
break;
}
if($passThis === true)
{
print "<option value='$idx'>$animal</option>";
}
}
print "</select>";
}
?>

mysql query to php array and display the array

$query2 = "SELECT * FROM `Listing` WHERE listingid = '{$myID}'";
if(!($result2 = # mysql_query($query2,$connection)))
echo "query failed<br>";
$result_array = array();
while($row2 = mysql_fetch_assoc($result2))
{
$result_array[] = $row2;
}
foreach ($result_array as $key => $val) {
echo "$key = $val\n";
}
Listing (Table) has 7 fields.
I get a bunch of "0 = Array"
How do I store mysql query results into php array and display them?
I want to have it as array first so i can sort them.
You are actually storing them. The code you have listed is storing them in array of arrays to see them you can modify the for with:
foreach ($result_array as $key => $val) {
echo "$key = " . print_r($val, true) . "\n";
}
$val is actually an array containing all the fields of a row.

Multiple select by array

I have:
$selectedItem = '100,200,300';
And mysql load:
<select multiple="multiple" name="product_id">
<?php
$query = mysql_query("SELECT * FROM products ORDER BY id");
while($row = mysql_fetch_array($query)){
echo '<option value="$row[id]">$name</option>';
}
?>
</select>
And I need $selectedItem (three values) to be:
<option value="$row[id]" selected>$row[id]</option>
How can I do that? I just can't find the solution when the selectedItem more than 1.
You should make your $selectedItem variable an array (and name it plural since it can have multiple values; just my added preference =P):
$selectedItems = array(100, 200, 300);
Doing this, you'll be able to check if the current row's id is in the array or not (with in_array()) and then "select" that row:
while($row = mysql_fetch_array($query)) {
$selected = in_array($row['id'], $selectedItems) ? ' selected="selected"' : '';
echo '<option value="' . $row[id] . '"' . $selected . '>' . $row['id'] . '</option>';
}
Alternatively, if you can't "define" your list of selected items as an array and you will only have a comma-separated string, you can use explode() to turn it into an array:
$selectedItems = explode(',', $selectedItem);
This will split the $selectedItem variable by commas into an array stored into $selectedItems (usable with the above code).
You can do it like this:
while($row = mysql_fetch_array($query)){
if ( str_pos( $selectedItem.',' , $row[id].',' ) !== false) {
$sel = 'selected';
} else {
$sel = '';
}
echo "<option value='$row[id]' $sel>$row[id]</option>";
}

PHP Sorting results of a Loop and displaying onscreen

I was wondering if someone could point me in the right direction with a coding issue Im having.
I am running a while loop in PHP comparing a post code to another and each run of the loop generates distance data. What Id like to do is then sort this data and display it.
Usually I'd throw everything into a MySQL database then sort that way but I think thats over kill.
Here's an example of the loop :
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
echo $row['instructor_name'] . " - " . $info['distance'];
}
I know this is probably PHP 101 but Ive never had to do anything like this before and am not sure how.
Thanks in advance for reading,
Rik
I think this is what you mean:
$rows = array();
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$row['distance'] = $info['distance']; // store it in the array
$rows[] = $row;
}
Then use usort to sort the $rows array by the distance key.
What I'd recommend here is storing each distance result in an array and then apply a sort to the array. For example:
$distances = array();
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$distances[$info['distance']] = $row['instructor_name'] . " - " . $info['distance'];
}
if(ksort($distances)) {
foreach($distances as $key=>$value) {
echo $value;
}
}
Note that my solution will not work for you if an exact distance appears more than once in the array; If that seems likely then you might need a different array-based solution.
For more information on array sorting, see Sorting Arrays in the PHP manual.
$data = array();
while($row = mysql_fetch_assoc($result)) {
$info = get_driving_information($_POST['customerpostcode'], $row['instructor_postcode']);
$data[$row['instructor_name']] = $info['distance'];
}
asort($data);
foreach ($data as $instructor => $distance) echo "$instructor - $distance<br />\n";
This will sort by instructor name. If you need to sort by distance, just reverse the way data is stored in the temporary array, I.E. $data[$row['distance']] = $info['instructor_name'];.
This will not work if the value you use as the temporary array key appears more than once, for that you would have to use array_multisort().
$data = $instructors = $distances = array();
for ($i = 0; $row = mysql_fetch_assoc($result); $i++) {
$info = get_driving_information($_POST['customerpostcode'], $row['instructor_postcode']);
$instructors[$i] = $row['instructor_name'];
$distances[$i] = $row['distance'];
$data[$i] = array('instructor'=>$row['instructor_name'],'distance'=>$info['distance']);
}
array_multisort($instructors,SORT_DESC,$distances,SORT_ASC,$data);
foreach ($data as $entry) echo "{$entry['instructor']} - {$entry['distance']}<br />\n";
This will work even if you have same instructor_name or distances several time in the array. Additionally buy modifying cmp() function you can sort whole thing by any other criteria.
$drivers = array();//initialising an array
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$drivers[]=row;//adding new item to array
}
$drivers = usort($drivers,'cmp'); // sorting array using custom comparison function "cmp()"
foreach ($drivers as $driver) //printing results
echo $driver['instructor_name'] . " - " . $driver['distance'];
//custom comparison function
function cmp($a, $b) //returns +1 if $a > $b, -1 if $a < $b, else returns 0
{
if ($a['distance']>$b['distance'])
return 1;
if ($a['distance']<$b['distance'])
return -1;
return 0;
//quicker solution is to "return $a['distance']-$b['distance'];"
}

Echo values of arrays?

I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}

Categories