array of data in a drop down menu - php

I am trying to get the area table of my database to display in a drop down menu but I am having trouble because it is an array.
In my controller I have: $data['city'] = $this->location->fetchCity();
but in my view when I go <?php echo $city; ?> I get this Array why?
Model:
public function fetchCity(){
$this->db->select('area');
$this->db->from('suburbs');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$row = $query->result();
}
Update:
<select>
<?php foreach ($city as $key => $row): ?>
<option value="<?php echo $row['area'];?>"><?php echo $row['area'];?></option>
<?php endforeach; ?>
</select>

<?php echo $city[$key]; ?>
OR
<?php echo $city['area']; ?>
Since your function call returns an Array, this is how I suggest you print it out.
foreach ($city as $key=>$row)
{
echo $row->area;
}
Since your result is an Array of Objects, I'm sure this will get things right.

Related

More than two variables in a foreach loop

I need some information regarding whether or not we can put more than two variable in a foreach loop. Do keep in mind I'm still a complete newbie :D
For example, I'm getting the data of the variable from a database with comma's
<?php
while($segment = $results->fetchRow()) {
$seg = explode(',', $segment['name']);
$section = explode(',', $segment['sek_id']);
$array = array_combine($seg, $section);
foreach($array as $out => $key){
if($out != ""){
?>
<option value="<?php echo $key; ?>"><?php echo $out; ?></option>
and here I managed to put two variables into my foreach loop.
Is there any way with it while still using a foreach loop? Like maybe if I have an 'id=""' where I would put the id's that is in comma's in it?
You can use following way.
<?php
$results = $results->fetchRow();
foreach($results as $result)
{
if(!empty($result['name']))
{
?>
<option value="<?php echo $result['sek_id']; ?>">
<?php echo $result['name']; ?>
</option>
<?php
}
}
<?php
That will be great if you can provide result of $results->fetchRow();
Let me know in case of any query.

Array returns "Array"

This is my first time trying to create an array but it's not going so well.
My code scans every $_POST in a form when pressing a submit button below an input field. What I wanted it to do was to only fetch the content of a "filled" input. Well life's full of disappointments so then I tried to remove all the empty array elements. But instead of doing that, it echos the word "Array".
I've always been bad at arrays, ever since my C# days and I've never known why because they always look so simple. If anybody can tell me what I'm doing wrong, I'd appreciate it.
PHP code that goes above the <html>
<?php
//This is what I've tried before
//$klant = array();
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord') {
$id = substr($k,10);
$klant[] = $v;
$klant = array_filter($klant);
echo $klant;
}
}
?>
Markup
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<?php
$query = ("select * from table1");
$result = mysqli_query($con, $query) or die (mysqli_error());
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row['rowid'];
?>
<tr><!--There are multiple rows, that's why I'm using foreach($_POST as $k => $v)-->
<td>
<input class="newRecord<?php echo $id; ?>" type="text" name="newRecord<?php echo $id; ?>" />
<a href="?record=<?php echo $id; ?>">
<button class="saveRecord<?php echo $id; ?>" name="saveRecord<?php echo $id; ?>">Save</button>
</a>
</td>
</tr>
<?php } ?>
</table>
</form>
You cannot echo arrays use print_r or var_dump
for Pretty-printing arrays try this
echo "<pre>";
print_r($your_array);
echo "</pre>";
I believe this is what you want!
<?php
$klant = array();
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord' && trim($v)) {
$id = substr($k,10);
$klant[$id] = $v;
}
}
echo "<pre>";var_dump($klant);echo "</pre>";
?>
But I am not that confident that I understand the question clearly. Can you clarify a bit more than this(if this is not what you desire)?
Change this :
echo $klant;
To this :
print_r($klant);
Or this :
var_dump($klant);
echo is just for strings, print_r and var_dump will echo anything (strings, arrays, objects etc).
EDIT for OP EDIT :
This will remove anything that is empty inside the array :
foreach ($klant as $key => $value)
if (empty($value))
unset($klant[$key]);
print_r($klant);
Try this
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord') {
$id = substr($k,10);
$klant[] = $v;
}
}
var_dump($klant);

Query result giving out more than it should

I have this code in my class:
public function get_data(){
$sql = "select id_especialidad, descripcion from especialidad";
foreach($this->dbh->query($sql) as $row)
{
$this->rows[] = $row;
}
return $this->rows;
}
Now I use it from HTML file like this:
<select>
<?php
$datos = $db->get_data();
for($i=0;$i<sizeof($datos);$i++)
{
?>
<option value="<?php echo $datos[$i]["id_especialidad"]?>"><?php echo $datos[$i]["descripcion"]?></option>
<?php
}
?>
</select>
Now in the browser I see the select with the rows but in the first row is says: "Notice: Undefined index: descripcion in (file_path)"
I have 9 rows in my table but when I put this "print sizeof($datos)" it shows 11 rows.
What is happening?
is there another way to show this data?
Thanks!
Since I don't know where and how you're using or re-using $this->rows[] as you haven't posted about it, I will change a bit your code:
public function get_data()
{
$sql = "SELECT id_especialidad,
descripcion
FROM especialidad";
$result = array();
foreach($this->dbh->query($sql) as $row)
{
$result = $row;
}
return $result;
}
Given $this->dbh->query is the PDO query, if you print_r the result you get from get_data it should give you something similar to:
Array(
[0]=>Array([id_especialidad]=>1
[0]=>1
[descripcion]=>test
[1]=>test
)
[1]=>Array([id_especialidad]=>2
[0]=>2
[descripcion]=>test2
[1]=>test2
)
)
And you can easily read it like this:
<select>
<?php
$data = $db->get_data();
foreach ($data as $item)
{
?>
<option value="<?php echo $item["id_especialidad"]; ?>"><?php echo $item["descripcion"]; ?></option>
<?php
}
?>
</select>
If you're getting more than 9 results where it should have been only 9 I can only think there might be a problem with $this->rows[] not being cleared after used or something alike.

multiple select in 2 dimensional array in php

In PHP, I am having 2 array
$ex1 = array(a,b,c,d,e,f,g,h);
$ex2 = array(c,e,f);
Here how can I integrate this with multiple select option in PHP page
Here ex1 is the multiple select array like
<select multiple name=slt[]>
</select>
And ex2 values are the chosen listing options
Something like:
<?php
$ex1 = array('a','b','c','d','e','f','g','h');
$ex2 = array('c','e','f');
echo "<select multiple name=slt[]>";
foreach($ex1 as $val){
//in_array() checks if value from 1st array ($val) is present
//anywhere in the second array ($ex2)
//if yes, that option will be selected. I'm using ternary operator
//here instead of if statement
$selected = (in_array($val,$ex2))?' selected':'';
echo "<option value='".$val."'$selected>".$val."</option>";
}
echo "</select>";
?>
PHP Demo
Output Fiddle
I'm not sure about what you want to do, but here's an idea :
$ex1 = array("a","b","c","d","e","f","g","h");
echo "<select multiple>";
foreach( $ex1 as $value ){
echo "<option value='$value'>$value</option>";
}
echo "</select>";
Try running it:
<?php
$ex1 = array('a','b','c','d','e','f','g','h');
$ex2 = array('c','e','f');
?>
<select multiple name=slt[]>
<?php
foreach ($ex1 as $option) {
$active = false;
foreach($ex2 as $selected){
if($option == $selected){
$active = true;
}
}
?>
<option value="<?php echo $option; ?>" <?php if($active===true) echo "selected"; ?>><?php echo $option; ?></option>
<?php
}
?>
</select>

Extracting image value from Array in Codeigniter

I'm having issues extracting a value from an array of images via Codeigniter/MySQL. So i have a table called "image" in my database and if i echo out it i get the following code:
{"f01efdf6fe3b2bb387d3094aa701203f":{"filename":"f01efdf6fe3b2bb387d3094aa701203f.jpg","alt":"","caption":"","primary":true},"b11581adadd1848acb2898e7a284afc1":{"filename":"b11581adadd1848acb2898e7a284afc1.png","alt":"","caption":""},"2cfee6d3c334696833b1cfe13910fcf1":{"filename":"2cfee6d3c334696833b1cfe13910fcf1.png","alt":"","caption":""}}
As you can see there are 3 images there, what i need is to echo out just the image where "primary" value is:true within a foreach loop...
EDIT:
<?php
$query = $this->db->query("SELECT * FROM offers_products WHERE offer_large LIMIT 5;");
?>
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li><!-- THIS IS THE IMAGES TABLE VALUE --> <?=$row->images?> <!-- --></li>
<li><?=$row->description?></li>
<?php endforeach; ?>
Maybe:
$array = json_decode($stringFromDatabase, true);
$primary = false;
foreach ($array as $longStringDontCare => $imageArray) {
if (!empty($imageArray['primary'])) {
$primary = $imageArray;
break;
}
}
if ($primary) {
echo $primary['filename'];// should give: f01efdf6fe3b2bb387d3094aa701203f.jpg
}
To give you one last hint:
<?php
function getPrimaryImageFromJsonString($stringFromDatabase) {
$array = json_decode($stringFromDatabase, true);
$primary = false;
foreach ($array as $longStringDontCare => $imageArray) {
if (!empty($imageArray['primary'])) {
$primary = $imageArray;
break;
}
}
if ($primary) {
return $primary['filename'];
}
return null;
}
?>
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li><?php echo getPrimaryImageFromJsonString($row->images);?></li>
<li><?=$row->description?></li>
<?php endforeach; ?>
L.E: a few edits.
You have to first decode the json encoded string and extract the primary image from there:
Here is small function which you can use to extract the primary image:(You can place this function in Helper if you are using CodeIgniter)
function get_primary_image($encode_json_data)
{
$primary_image = '';
$decoded_json = json_decode($encode_json_data);
foreach($decoded_json as $obj)
{
if(isset($obj->primary) && $obj->primary == 1)
$primary_image = $obj->filename;
}
return $primary_image;
}
You can call above function in your view in following way:
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li> <?=get_primary_image($row->images)?></li><!-- Here, you call above function -->
<li><?=$row->description?></li>
<?php endforeach; ?>

Categories