Two foreach use with a array [duplicate] - php

This question already has answers here:
How can I loop through a MySQL result set more than once using the mysql_* functions?
(7 answers)
PDO multiple fetching of same query [duplicate]
(2 answers)
Closed 3 years ago.
I have a array and i use two foreach but I be only able to print the first foreach.
$test = $db->query("SELECT * FROM Test");
foreach ($test as $readTest) {
echo $readTest["col1"];
}
foreach ($test as $readTest) {
echo $readTest["col2"];
}
and I try with this:
$test1 = $test;
$test2 = $test;
I expect the output of $readTest["col1"] and $readTest["col2"], but the actual output is $readTest["col1"]

Use #fetchAll to get all your result in a conventional array. You will then be able to loop on them multiple times.

Why use array, when you can print this way:
$test = $db->query("SELECT * FROM Test");
while($PrintTest = $test->fetch_object())
{
echo $PrintTest->col1;
echo $PrintTest->col2;
}
Even if you want to use Arrays, you can do something like this:
$Array1 = array();
$Array2 = array();
$test = $db->query("SELECT * FROM Test");
while($PrintTest = $test->fetch_object())
{
$Array1[] = $PrintTest->col1;
$Array2[] = $PrintTest->col2;
}
And then, you can run through the array with For or Foreach

Related

PHP implode named array [duplicate]

This question already has answers here:
Imploding an associative array in PHP
(10 answers)
Closed 8 years ago.
I have a named array that look like this:
$arr = array('name'=>'somename','value'=>'somevalue');
I want to turn that array into something like this:
name='somename' value='somevalue'
I tried http_build_query() to do it.
echo http_build_query($arr, '', ' ');
But this is the result I get:
name=somename%21 value=somevalue%21
How can I get the result I want with http_build_query()? Or, is there any PHP function to do it?
Thank you.
http_build_query returns a urlencoded string. If you don't want that you can run it through urldecode
$arr = array('name'=>"'somename'",'value'=>"'somevalue'");
print urldecode(http_build_query($arr,null,' '));
Try with foreach()
$arr = array('name'=>'somename','value'=>'somevalue');
$str = '';
foreach($arr as $k=>$v) {
$str.= "$k='$v' ";
}
echo $str;
foreach ($array as $key => $value) {
$result .= "$key='$value' ";
}
echo rtrim($result,' ');

How to mutiply all values in a PHP foreach array [duplicate]

This question already has answers here:
Multiply each integer in a flat array by 60
(5 answers)
Closed 9 years ago.
i want to mutiply all the values in a foreach array by itself
here is an example of the array
Array ( [0] => 2.4 [1] => 6 )
, all i want to do is mutiply 2.4*6
foreach($pp_events as $key=>$value)
{
#echo $value;
$pick=mysql_query("select * from pick where eventid='$value'");
$row=mysql_fetch_array($pick);
$sum*=$row['startPrice'];
}
There's no need to implement this yourself. PHP has a built-in function for multiplying all the values in an array - array_product(). Use that instead:
$products = array();
foreach ($pp_events as $key => $value) {
$pick = mysql_query("select * from pick where eventid='$value'");
$row = mysql_fetch_array($pick);
$products[] = $row['startPrice'];
}
echo array_product($products);
See also:
Why shouldn't I use mysql_* functions in PHP?
You need to initialize the variable to 1, then your loop should work.
$product = 1;
foreach ($pp_events as $key => $value) {
$pick = mysql_query("select * from pick where eventid='$value'");
$row = mysql_fetch_array($pick);
$product *= $row['startPrice'];
}
echo $product;
You can also do a single query, instead of a separate query for each value:
$events = implode(',', array_map(function($x) { return "'$x'"; }, $pp_events));
$pick = mysql_query("select startPrice from pick where eventid IN ($events)");
$product = 1;
while ($row = mysql_fetch_assoc($pick)) {
$product = $row['startPrice'];
}
echo $product;

How can I iterate through two arrays at the same time without re-iterating through the parent loop? [duplicate]

This question already has answers here:
php looping through multiple arrays [duplicate]
(8 answers)
Closed 9 years ago.
How can I iterate through two arrays at the same time that have equal sizes ?
for example , first array $a = array( 1,2,3,4,5);
second array $b = array(1,2,3,4,5);
The result that I would like through iterating through both is having the looping process going through the same values to produce a result like
1-1
2-2
3-3
4-4
5-5
I tried to do it this way below but it didn't work , it keeps going through the first loop again
foreach($a as $content) {
foreach($b as $contentb){
echo $a."-".$b."<br />";
}
}
Not the most efficient, but a demonstration of SPL's multipleIterator
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));
$newArray = array();
foreach ( $mi as $value ) {
list($value1, $value2) = $value;
echo $value1 , '-' , $value2 , PHP_EOL;
}
Use a normal for loop instead of a foreach, so that you get an explicit loop counter:
for($i=0; $i<count($content)-1; $i++) {
echo $content[$i].'-'.$contentb[$i];
}
If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the foreach construct
foreach($content as $key=>$item) {
echo $item.'-'.$contentb[$key];
}
If they're the same size, just do this:
foreach($a as $key => $content){
$contentb = $b[$key];
echo($content."-".$contentb."<br />");
}

ksort on multidimensional array [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 9 months ago.
I have a multidimensional array, and I need to sort that array by a specific key in that array.
I add to the array like this in a for loop
$myArr[$i][0] = $row[1];
$myArr[$i][1] = $row[2];
$myArr[$i][2] = $row[3];
Now lets say that the value of $row[3] is DATE_ATOM.
How can i arrange the completed array by $myArr[$i][2]?
Thanks!
What you are probably looking for is array_multisort(), specifically this example usage (Sorting database results).
For example (based on your code above):
$i = 0;
$myArr = $col1 = $col2 = $col3 = array();
foreach ($rows as $row) {
$myArr[$i][0] = $col1[$i] = $row[1];
$myArr[$i][1] = $col2[$i] = $row[2];
$myArr[$i][2] = $col3[$i] = $row[3];
$i++;
}
array_multisort($col3, SORT_ASC, $myArr);
var_dump($myArr);

Multiple array echo with foreach statement in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Multiple index variables in PHP foreach loop
Can we echo multiple arrays using single foreach statement?
Tried doing it in following way but wasn't successful:
foreach($cars, $ages as $value1, $value2)
{
echo $value1.$value2;
}
assuming both arrays have the same amount of elements, this should work
foreach(array_combine($cars, $ages) as $car => $age){
echo $car.$age;
}
if the arrays are not guaranteed to be the same length then you can do something like this
$len = max(count($ages), count($cars));
for($i=0; $i<$len; $i++){
$car = isset($cars[$i]) ? $cars[$i] : '';
$age = isset($ages[$i]) ? $ages[$i] : '';
echo $car.$age;
}
if you just want to join the two arrays, you can do it like this
foreach(array_merge($cars, $ages) as $key => $value){
echo $key . $value;
}

Categories