Can you use a for loop to create array names? - php

I am pulling data from a database and I want to create array names on the fly.....group1, group2...etc using a for loop. I wonder if this is possible at all? The code below obviously doesn't work and I'm only including it to demonstrate what I'm trying to do. Any help would be much appreciated!
<?php
for ($i=1; $i <=40; $i++){
$group.$i = [];
}
?>

Its not so much "array names" that you are looking for as a much as a nested array. $group[$i] would give you a nested array. eg
for ($i=1; $i <=40; $i++){
$group[$i] = [];
}
$group[1][] = 'foo';
echo $group[1][0];
// prints: foo

Something like this ? This works 100%
// $result = $conn->query($sql);
$i = 0;
$all = array();
while($row = $result->fetch_assoc()) {
$i++;
$arr[$i]['id'] = $row['id'];
$arr[$i]['firstname'] = $row['first_name'];
$arr[$i]['lastname'] = $row['last_name'];
$all[] = $arr[$i];
}
echo '<pre>';
echo print_r($all);

Related

When using while loop to fetch database results, how do i jump to the third row and get the number

while ($row = mysqli_fetch_assoc($result)) {
$price6 = substr("{$row['price']}",0,15);
}
for example in this code if its going to print out five results, i want to do something immediately after the third result is printed out. Please someone help me out.
You can either have a variable $i = 0 before the loop and count it in the loop and after let say $i == 3 you can write break and go out of the loop OR your can write a for loop and do the same:
Example 1:
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
$price6 = substr("{$row['price']}",0,15);
$i++;
if ($i == 3) break;
}
Example 2:
$row = mysqli_fetch_assoc($result);
for ($i = 0; $i < count($row); $i++) {
// do something
if ($i == 3) break;
}
I haven't tested this on your example but just to give you an idea.
The other suggestions here are good, here's another way of doing it:
Replace your while loop with the following:
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
Now you can use that array in foreach loops like so
foreach($rows as $id => $row){
//id is now the "count"
//keep in mind it starts from zero
}
Did you try adding a counter?
$teller=0;
while ($row = mysqli_fetch_assoc($result)) {
$price6 = substr("{$row['price']}",0,15);
if ($teller == 3) {
// do something magical
}
$teller++;
}

PHP: Create Unique Variables In A For Loop

I was wondering if it is possible to create unique variables in a for loop using PHP. I tried the following code but it didn't work:
$level_count = 6
for ($i=1; $i<=$level_count; $i++) {
$level_ + $i = array();
}
I would like to end up with the variables $level_1, $level_2, $level_3, $level_4, $level_5 and $level_6. How would I achieve this?
$level_count = 6
for ($i=1; $i<=$level_count; $i++) {
$l = "level" . $i;
$$l = array();
}
But Zerkms is right...
$arr = array(array(),array(),array(),array(),array(),array());
It's much easier if you use arrays for this. Try this one-liner:
$level_count = 6;
$array = array_fill_keys(array_map(function($index) {
return 'level_' . $index;
}, range(1, $level_count)), array());
var_dump($array);
Weird thing (I have no idea why you want to use it), but, just for educational purposes...
$level_count = 6;
for ($i = 1; $i <= $level_count; $i++) {
$name = 'level_' . $i;
$$name = array();
}

mysql_fetch_array while loop

I have a while loop that contains another while loop. Both loops are iterating over different mysql result sets. The problem is that the second time the outer while loop calls the inner while loop it doesn't run. Does Mysql_fetch_row discard itself after it has been iterated over?
Here is what the code looks like:
$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
while($d = mysql_fetch_row($dictionary)){
$key = $d[0];
for($i= 0; $i< count($tableColumNames); $i++){
if($tableColumNames[$i] == $key){
$col .= "`".$d[1]."` ,";
$val .= "`".$r[$i]."` ,";
/* echo $tableColumNames[$i]." table ColumnName <br>";
echo $d[1]." key<br>"; */
}
}
echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}
And here is what the output is like: You can see that the $result holds four records and the output is showing that the loop is working correctly. However, the inner loop over the $dictionary result set doesn't run the second time $result is being iterated over. Any ideas why? I tried to use mysql_fetch_array as well but still the same result.
Thanks
When ever you are calling mysql_fetch_row($dictionary) It gives you a particular column details in the row and it deletes it from the $dictionary array.
So there are no elements for next use.
Instead of declaring $dictionary outside declare it in while loop. It will solve your problem.
$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
$dictionary=("Select * from database");//your own logic
while($d = mysql_fetch_row($dictionary)){
$key = $d[0];
for($i= 0; $i< count($tableColumNames); $i++){
if($tableColumNames[$i] == $key){
$col .= "`".$d[1]."` ,";
$val .= "`".$r[$i]."` ,";
/* echo $tableColumNames[$i]." table ColumnName <br>";
echo $d[1]." key<br>"; */
}
}
echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}
or you can use mysql_data_seek().

How can I store results from MySQL to PHP array?

I tried storing data to php array from mysql using under code. But it's not working.
This code:
echo $answerArray[count][i];
shows the correct result. But this code:
echo $answerArray[0][0];
doesn´t show anything.
What should I do to fix it?
Thank you.
Full code:
$count = 0; //answer count
$answerArray = array();
while ($row = mysqli_fetch_array($resultFromR, MYSQLI_ASSOC)) { //add array from db
for($i = 0; $i < $questionNumber; $i++) {
$j = $i + 1;
$answerArray[count][i] = $row["num$j"];
echo $answerArray[count][i]; //is working.
}
$count++;
}
echo '<br />';
echo $answerArray[0][0]; //something wrong!!! I cannot get anything from this.
maybe this will work
$answerArray[$count][$i] = $row["num$j"];
(add $ before count and i)
Not sure but shouldn't the [i] be [$i]?

how do i reverse the order when echoing my results?

i have this bit of code:
<?php
$file = file_get_contents('http://example.com');
preg_match_all("/<a href=(.*?links.*?)>.*?<\/a>/i", $file, $a);
$count = count($a[1]);
for ($row = 0; $row < $count ; $row++) {
$linkurls = $a[1]["$row"];
echo ' '.$linkurls.' <br>';
}
?>
and currently it echos the links in order they appear on the website. I would like for it to echo the results in a reverse order (the last link on example.com to echo as the first with this code)
any help is appreciated! thanks.
for ($row = $count - 1; $row > -1 ; $row--) {
$linkurls = $a[1]["$row"];
echo ' '.$linkurls.' <br>';
}
PHP has a function for it: array_reverse.
$a[1] = array_reverse($a[1]);
Also why would you use ["$row"] instead of [$row]? There is no functional difference as numeric strings get converted back to numbers when using them as indexes, so don't worry about that, but just because something can be done doesn't mean you should do it.
<?php
$file = file_get_contents('http://example.com');
preg_match_all("/<a href=(.*?links.*?)>.*?<\/a>/i", $file, $a);
$a = array_reverse($a);
$count = count($a[1]);
for ($row = 0; $row < $count ; $row++) {
$linkurls = $a[1]["$row"];
echo ' '.$linkurls.' <br>';
}
?>

Categories