How to copy an associative array inside another associative array in PHP - php

Can anyone tell me how to store an array of associative arrays? I thought this code would work, but it's not. I tried researching it but couldn't find an answer.
foreach($rows as $row) {
// Some SQL...
if ($stmt->execute()) {
while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['NestedResults'][] = $row2;
}
}
}
foreach ($rows as $row) {
foreach ($row['NestedResults'] as $results) {
echo $results['Item'] . '<br>';
}
}
PS: I know I shouldn't loop SQL statements like that, but it's a special case.

In your first foreach loop, you need to pass the $row variable by reference, otherwise you are just modifying a copy of the element from $rows stored in $row:
foreach($rows as &$row)

do you think it is workable to put the second loop inside the first one as below?
$row['NestedResults'][] = $row2;
foreach ($row['NestedResults'] as $results) {
echo $results['Item'] . '<br>';
}
not 100% sure...

Related

Mysqli_fetch_array not working for forearch loop

I'm trying to fetch data and display it via foreach loop but it's not working giving argument error but when i try this with while loop it's work fine. so my question is that why i cannot fetch data using mysqli_fetch_array with foreach why it's only possible with while loop
// While
while($row = mysqli_fetch_row($result))
{
var_dump($row); echo "<hr />";
}
// Foreach
foreach(mysqli_fetch_array($result) as $row)
{
var_dump($row); echo "<hr />";
}
You can't use foreach for mysqli_fetch_array directly.
Foreach is a loop using for an exist array, to loop through each its item
You can use like below
$result = array();
while($row = mysqli_fetch_array($result)) {
$result[] = $row;
}
foreach($result as $row) {
var_dump($row);
echo "<hr />";
}
Because mysqli_fetch_array as comes from it's name - fetches one row of your result as array.
So, foreach(mysqli_fetch_array($result) as $row) means
Fetch one row and iterate over this row.
While while($row = mysqli_fetch_row($result)) means
Do fetching rows until there's nothing to fetch.
And when there's nothing to fetch while-condition is false and the loop breaks.
Info about while-loop and foreach-loop

Php - Array to string conversion

I want to output all records in my database. So far so good, but when I loop through it, php gives me an error " Array to string conversion ".
I added an index to the array but then it does just output obviously the first or secound ( etc. ) column.
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result[0] as $value)
{
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
So, with the index, it does work. But I need all records, not just one.
I appreciate every comment and help!
I would start with a nested loop. I also wonder if you want a table for every value
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result as $row){ //Go through every row in the result
echo('<table>');
foreach ($row as $value){ //Go through every value in the row
echo "<tr><td>'$value'</td></tr>";
}
echo('</table>');
}
}
This will print every row as a new table, but you can search out the variation you want.
A nested foreach loop should work.
foreach ($result as $values)
{
foreach ($values as $value) {
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
An alternative to nested loops, if you know the number of fields and said number is constant for each execution; A state that's found in most situations; You can use vsprintf () to print out the rows.
Quick example:
$result = {{'John', 'Doe'}, {'Sarah', 'Jane'}};
$output = '<table>';
foreach ($result as $row) {
$output .= vsprintf ("<tr><td>%s</td><td>%s</td></tr>\n", $row);
}
echo $output."</table>";
Cuts down a bit on the code, and quite a bit on the code complexity. The template for the rows themselves can also be extracted to a variable (or template view), outside of the loop, to make the code even cleaner.

Compare for existing values from 2 foreach loops?

I have 2 foreach loop's where i get new results from my first db and i have second foreach where i get data from second db
My first foreach code is:
foreach($_existing_data_result as $result) {
echo $result->name.'<br>';
}
second foreach:
foreach($_new_data_result as $resultNew) {
echo $resultNew->name.'<br>';
}
I need to check on second foreach if result exist in first then ignore this result, i tried it with in_array()but i always see double names...
Second foreach, change it to this:
foreach($_new_data_result as $resultNew) {
if (!in_array($resultNew,$_existing_data_result))
echo $resultNew->name.'<br>';
}
This will work assuming that entire $resultNew object exist in $_existing_data_result and is identical.
//Use array_diff instead. Like
$new_array = array_diff($_existing_data_result, $_new_data_result);
First get all names from the first array:
$names = array_map(
create_function('$object', 'return $object->name;'),
$app_items);
Then in second foreach check if the name exists in names array:
foreach($_new_data_result as $resultNew) {
if(!in_array($resultNew->name, $names) {
echo $resultNew->name.'<br>';
}
}
$names = array();
foreach($_existing_data_result as $result) {
echo $result->name.'<br>';
$names[$result->name] = 1;
}
foreach($_new_data_result as $resultNew) {
if (!isset($names[$resultNew->name])) {
echo $resultNew->name.'<br>';
}
}

Obtaining data from query in multidimensional array

I have spent a lot of time trying to find ways to do the following, and have researched as much as I can but am still stuck.
I have a table 'pool_a' that at the minute has 2 columns - team_id and team_name.
I need to echo the id and the name into a nested foreach loop.
Now I can do this if I am just worried about the name, but now my query includes the ID too, I can't work out how to get both bits of data for each row in my table.
Here's how I get it to work with team_name...
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[$i] = $team;
echo $team . "<br>";
}
foreach ($team_names as $team) {
foreach ($team_names as $opposition) {
if ($team != $opposition) {
echo "<tr><td>" . $team . "<td><input type=\"text\"<td>versus<td><input type=\"text\">" . $opposition . "</tr>";
}
}
}
This is great, and outputs the correct fixture list and with input boxes for scores, but I need to add a hidden data input with team_id as the value. For example:
Here is what I have so far. Note that I have been learning about PDO's and new 5.5 techniques, so you will notice my style of code will be different in the next snippet.
require_once "pdo_enl_connect.php";
$database=dbNB_connect();
$query=$database->query ("SELECT team_id, team_name from pool_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
printf ("%s %s<br>", $row[0], $row[1]);
$teams=array($row[0], $row[1]);
}
foreach ($teams as $key=>$value) {
echo "$key and $value<br>";
}
$database=NULL;
The output I get for the foreach loop is
0 and 5
1 and Silhouettes //silhouettes being the last team in the table.
ANy help would be much appreciated, and please let me know if I can edit my question to make it clearer in any way.
Thanks
Your while loop should look like this:
$teams = array();
while ($row = $query->fetch(PDO::FETCH_NUM)) {
// $row and array($row[0], $row[1]) are the same here
$teams[] = $row;
}
You need to initialize $team = array(); before your loop.
Then add your tuple to the teams array by doing either array_push($teams, array($row[0], $row[1])); or $teams []= array($row[0], $row[1]);`

How to stop a while loop from running infinatly by making it stop when there are no more values in the array

I am trying to make pull key => value pairs out of an array by using a do { ....} while {there are values left inside the array.
I am using a function to query mysql for and then to insert all the values inside an array
function table_array($query) {
$table_array = array();
$data_fetched = false;
while ($array = mysql_fetch_assoc($query)) {
if (!$data_fetched) {
foreach ($array as $key => $value) {
$table_array[$key] = $value;
//$data_fetched = true;
}
}
}
return $table_array;
}
and then i am using another loop to extract the data from the array
function get_table($table_array) {
$header_written = false;
echo "<table border=1>";
if ($table_array) {
do {
echo "<tr>";
foreach ($table_array as $columns => $values) {
echo "<td> {$values} </td>";
}
echo "</tr>";
}while ($table_array);
}
echo "</table>";
}
However this causing my loop to run infinitely , why can't i use it just as though i would be doing while mysql_fetch_assoc is true.
I tried using a flag but that will stop it running after only one record is being extracted.
What you really need here are two foreach loops. The outer iterates over rows, and the inner iterates over columns:
echo "<table>";
// Iterates over rows
foreach ($table_array as $row) {
echo "<tr>";
// Iterates over columns (table cells)
foreach ($row as $col=>$value) {
echo "<td>{$value}</td>";
}
echo "</tr>";
}
echo "</table>";
Though your fetching process works, it can be simplified and improved. You don't need a foreach to assign columns to your $table_array. You can simply append the whole fetched row using the [] syntax. Not sure what the purpose of $data_fetched was, so I removed that as well
while ($array = mysql_fetch_assoc($query)) {
// Use the [] syntax to append the whole row onto $table_array
// No need to add each column of the fetched row separately
$table_array[] = $array;
}
Finally, the reason it didn't work the way you setup your do-while is that iterating over a regular array is not similar to fetching from a MySQL result set. The fetch calls will eventually return FALSE when no rows remain. Unless you are actively removing elements from an array while iterating over it, and eventually deleting the empty array, it will always evaluate to a boolean TRUE.
You need to use either foreach($array as $key => $value){ ... } or do{ ... } while ($array).
You should not use both, as you only have one set of data to loop over. I would stick with foreach as it is safer, and can do exactly what you need.
If you feel you need to use a do/while, then you need to pop a value off the $table_array each time you are inside the loop. This way, the $table_array will become empty at some point. Currently, in your code, the $table_array is always full so the while loop continues endlessly.

Categories