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>';
}
}
Related
Im getting the array from a function then using it on a foreach, it prints all rows, how can i print specific row when im using [0] after array it displays only first letters of both rows.
PHP FUNCTION:
public function selectedOffer($model_id){
$qq = mysqli_query($this->connection,"SELECT offerId FROM offers WHERE model_id='$model_id' ORDER BY id ASC");
$results = array();
while ($result = mysqli_fetch_array($qq)) {
$results[] = $result;
}
return $results;
}
FOREACH PHP
foreach ($mUser->selectedOffer($modelid) as $key) {
echo $key['offerId'][0];
}
also when i remove the [0] it prints both rows.
My question is how to print the first or second or which row i want?
To get specific/ first row,s column
$data = $mUser->selectedOffer($modelid);
echo $data[0]["offerId"];
And all rows column
foreach ($data as $key) {
echo $key['offerId'];
}
Use implode and array_column to echo a complete array column in one line of code:
echo implode("", array_column($yourarray, "offerId"));
The first argument of the implode is what should join the items in the array.
Your and the accepted answer has nothing that is why it's "", but it can be replaced with say: "<br>\n" if you want new line between each item of the array.
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...
I am fetching data from my DB and they look like this:
[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]
where the key-1 are the name of the column. (I only have one entry so).
I want to extract only the column values and save them into a new array that will output like this:
{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}
I want it to look exactly like this and not : [{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}]
I tried this:
$cart["key-1"]=$output["key-1"];
where $output is the outcome of the DB that shown first (the one with []).
and the $cart is the new array I want.
Both are declared as:
$cart=array();
$output=array();
and $output[]=$row where row is the result of the DB fetch. How to do it?
Here's one way to do it, I've substituted the database row for a string here, and made use of json_decode() and json_encode()
$data = '[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]';
// convert to an array
$data = json_decode($data, true);
// create new array here
$cart = array();
for ($i = 0; $i < count($data); $i++)
{
foreach ($data[$i] as $k => $v)
{
if (strpos($k, 'key') !== FALSE)
{
$cart[$k] = $v;
}
}
}
echo $cart['key-1'] . '<br/>';
echo json_encode($cart);
Output:
1
{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}
This is a very chaotically asked question.
From what I gathered you want maybe this..?
$cart=array();
foreach ($output as $index=>$value){
if stripos($index,"key-"){
cart[$index]=$value;
}
}
Use mysql_fetch_assoc() to get only column names ;)
while ($row = mysql_fetch_assoc($result_of_query))
{
echo $row['key-1'];
echo $row['key-2'];
}
I'm experimenting with MySQLi and using the following code to check differences for how I should approach my array formatting/usage for fetch_array(MYSQLI_ASSOC);
here is my code:
include "Database.php";
$ArrayQuery = $mysqli->query("SELECT * FROM accountinformation");
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
The problem is, that i'm using the same Variable for my while loop, the first one returns 3 then 3 Which is expected.
But the problem is, with my second query; it returns a blank array
array( ) when print_r();
and when I do:
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
For my Second while loop, it returns nothing for output.
I have checked my variables $ArrayResults and $ArrayResult are not duplicates, they are in fact unique.
Why is my second while loop returning nothing when my first one is working?
Update
When I produce a second query into the mixture with a different starting variable:
$ArrayQuer = $mysqli->query("SELECT * FROM accountinformation");
and modify my second while loop:
while ($ArrayResult = $ArrayQuer->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
I get the expected output? So is it a case of MySQLi not allowing the same parameters to be used twice throughout the script?
mysqli_data_seek
Adjusts the result pointer to an arbitrary row in the
result
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
mysqli_data_seek($ArrayQuery,0); // Addition Made Here
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
To re-use an already fetched array; you should use mysqli_data_seek(); (Notice I have added it above your `$Empty Variable) This should be the problem.
See the manual here:
http://us.php.net/manual/en/mysqli-result.data-seek.php
Think of this scenario; Why would you re-buy something you already own?
Fits perfectly in your case
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.