Hey I have an array that contains an array:
$outPutResults = array();
while($row = mysqli_fetch_array($results))
{
$outPutResults[] = $row['industry'];
$outPutResults[] = $row['location'];
$outPutResults[] = $row['title'];
$outPutResults[] = $row['description'];
}
$searchResults[] = $outPutResults;
I am little confused how I would echo the contents.
As far as I am aware $outputresults[] should now be contained within $searchresults[].
To output the content I'm using :
foreach ($searchResults[0] as $item) {echo $item;}
But this is only echoing the first set of results so rather than having to repeat the above and changing the number (0) each time how would i do it so it outputs all the sub arrays?
Just nest your foreach:
foreach ($searchResults as $row) {
foreach($row as $item) {
echo $item;
}
}
$outPutResults = array();
$i = 0;
while($row = mysqli_fetch_array($results))
{
$outPutResults[$i] = $row;
$i++;
}
foreach ($outPutResults as $items)
foreach($items as $item)
echo $item;
Why are you doing
$searchResults[] = $outPutResults;
instead of just
$searchResults = $outPutResults;
Then you don't have to worry about nesting your foreach statements.
You should nest two loops. For example like this:
foreach ($searchResults as $array) {
foreach ($array as $item){
echo $item;
}
}
Related
$array = array();
while ($row = mysqli_fetch_assoc($result)) {
$user_id = $row["user_id"];
$user_name = $row["user_name"];
}
foreach ($array as $arr) {
echo $arr;
}
Above code echos all the values from the $array how can I get a specific value of this array.
For example something like this echo $arr[2] (but it doesn't work)
Please mention that I'm getting some data from mysql and my purpose by asking this question is to get each value from a column separately.
Thank you if you can help me.
You forgot to fill your array with data...
while($row = mysqli_fetch_assoc($result)){
$array[]= array($row["user_id"], $row["user_name"]);
}
And now you can access to your data
foreach($array as $arr){
echo $arr[0];
echo $arr[1];
}
If you need to get the specific value of an array. you can get by
$array[2]
not
$arr[2]
Please try
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
foreach($array as $arr){
print_r($arr);
}
$array = array();
while($row = mysqli_fetch_assoc($result)){
$user_id = $row["user_id"];
$user_name = $row["user_name"];
$array[] = $row;
}
And use $array[2] to get records in 2nd index.
OR
foreach($array as $arr){
echo $arr[0];
echo $arr[1];
}
Also useful is to use the $key=>$value in your foreach loop.
foreach ($array as $key=>$value) {
echo $key."->".$value."<br />";
}
This will list each of your array items with values and respective keys.
This is my code:
session_start();
/* loops through each row in the global $_SESSION variable which
contains the array and uses the $value to GET the data in the text
boxes and output them */
// studevent_result =
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
echo $studResult;
echo "<br>";
}
// result_postion =
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition = $_GET[$value];
echo $studPosition;
echo "<br>";
}
echo "<br>";
// stud_id =
foreach ($_SESSION['arrayId'] as $value) {
echo $value;
echo "<br>";
}
// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
UPDATE result
SET studevent_result = '00:20:33',
result_position = '6'
WHERE result.stud_id = '12'
";
$updateRow = mysqli_query($conn, $updateQuery);
I use $_SESSION variables which all store an array. I extract the results of these arrays using foreach loops.
In $updateQuery, I want to make studevent_result = to the results of my first foreach loop above, result_position = to the results of the second foreach loop above and the result.stud_id = to the results of the third foreach loop above.
After me editing the code my code now looks like this:
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
foreach ($_SESSION['arrayNamePosition'] as $data) {
$studPosition = $_GET[$data];
foreach ($_SESSION['arrayId'] as $idValue) {
echo $idValue;
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult',
result_position = '$studPosition'
WHERE result.stud_id = '$idValue'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
}
}
I nested the foreach loops. But the problem now is that for the last foreach loop in the nested loops, $idValue in the query only uses the last element in the array $_SESSION['arrayId']. How can I fix this to loop throught the whole array, so that the query uses all the values in the array?
Thanks in advance.
If I understood your issue this should help you
session_start();
$i = 0;
$studResult = array();
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult[$i] = $_GET[$value];
$i++;
}
$studPosition= array();
$i=0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
}
$stud_id = array(); $i=0;
foreach ($_SESSION['arrayId'] as $value) {
$stud_id[$i] = $value; $i++;
}
for($j =0; $j<$i; $j++){
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult[$j]',
result_position = '$studPosition[$j]'
WHERE result.stud_id = '$stud_id[$j]'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
Hope it will be helpful. Happy coding :)
I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}
I am trying to create a drop down menu of usernames or a <select> as it's known in HTML. However I am only getting the last value back from my array and I can't figure out why.
PHP
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
HTML
<select>
<?php $names = getUserName($db); foreach($names as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value ?></option>
<?php }?>
</select>
I'm fairly sure the HTML section of my code is solid. I think the error lies in how I'm adding values to my $names array but after staring at it for a half an hour I can't see it. Thanks for any help/fresh eyes.
You need to declare your array outside the loop
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
this is emptying your array every time : $names = array();
use this :
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
You are creating a new $names array every row then returning the last one. You need to declare the array outside the while loop. The following should work:
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
The problem is you're re-initializing the array on every loop:
See:
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
Should be:
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
I'm trying to get the value of $row->price for the last iteration in my for loop as below
foreach ($getprices->result() as $row)
{
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
I did try the following, however it didn't appear to work
$numItems = count($getprices->result());
$i = 0;
foreach($getprices->result() as $row) {
if(++$i === $numItems) {
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
}
}
Any suggestions?
Use $row->price just after the loop has ended:
foreach ($getprices->result() as $row)
{
// ...
}
$lastprice = $row->price;
This is really just a trick, but it will work. If you are iterating over an array you can also do it like this:
$array = $getprices->result();
foreach ($array as $row)
{
// ...
}
$lastprice = end($array)->price; // this will work independently of any loop
Add a line $lastitem=$row right after the for statement ; it will contain the last value after the loop is finished
You can use php end to get the last value of an array.
eg;
$arr = $getprices->result();
$last = end($arr);