PHP invalid argument in foreach loop - php

I have a main php file that I am including in my php file that I am calling the functions from.
My main file has this function
function GetComments()
{
global $server;
global $info;
global $dbhandle;
$query = "SELECT GbId, fname, lname, comment FROM Guestbook";
$result = sqlsrv_query($dbhandle, $query);
while($row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
{
$array[$row['GbId']] = array(
'f' => trim($row['fname']),
'l' => trim($row['lname']),
'c' => trim($row['comment']));
}
return $array;
}
and my webpage document has this code
<?php
$array = GetComments();
foreach($array as $key => $info)
{
echo $info['f']." ".$info['l']." said ".""".$info['c']."""."<br /><br />";
}
Close();
?>
This code works fine when the foreach loop is in the main file, but I get a warning after all the data is printed out when it is in the webpage file. I'm not too concerned about it as it still works, but I would like to either get rid of it, fix it, or at least know why it is happening.
Thanks

Error occurs because foreach expects array as input, but provided variable is not array at some piont.
Solution : If it is not array, make it a null array.
Try adding this line if(!is_array($array)){ $array = array(); } after $array = GetComments();
$array = GetComments();
if(!is_array($array)){ $array = array(); }
EDIT : Declare the array before while loop in your function
$array = array();
while($row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
{
$array[$row['GbId']] = array(
'f' => trim($row['fname']),
'l' => trim($row['lname']),
'c' => trim($row['comment']));
}
return $array;

you can use like this:
foreach( (array) $array as $key => $info)

Related

moved working routine to function, now results are not present

As I try to consolidate my code and make it more available to other projects, I've run into a problem:
variables that were generated and available are not anymore when that routine is moved to a function:
This is the query:
$count = "SELECT eid, Count, Name, name2, Email, pay FROM h2018";
THIS WORKS FINE:
$result = $mysqli->query($count);
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
echo($a." and ".$value."<BR>");
}
NOT WORKING FINE:
function avar($result) {
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
}
}
$result = $mysqli->query($count);
avar($result);
echo($a." and ".$value."<BR>");
I thought the variable variables would be available from outside of the function. I tried doing a return, but that didn't help. I also tried to global $$key, but that didn't work either.
What am I doing wrong?
There is multiple mistakes or missing steps like return or array
function avar($result) {
$data=array();
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$data[$key] = $value;//if there is multiple records then used array otherwise you should used variable
}
return $data;
}
$result = $mysqli->query($count);
$data=avar($result);//get return value
print_r($data);
Please, read the PHP documentation about the Variable Scope for more information. The variables inside your function are local so you cannot access them outside of your function. You would have to return something.
For example, this could work:
function avar($result) {
$resultArray = false;
$row = $result->fetch_assoc();
foreach ($row as $key => $value) {
$resultArray = [
'key' => $key,
'value' => $value
];
}
return $resultArray;
}
$result = $mysqli->query($count);
$queryResult = avar($result);
if ($queryResult) {
echo 'Key: ' . $queryResult['key'] . ' | Value: ' . $queryResult['value'];
}
Please do note that fetch_assoc will return an array with multiple items if there is more than one result. In my example only one (and the last) result will be returned.
Edit: As #Nigel Ren said in his comment. In this case you're basically rebuilding an array which is going to look (nearly) the same as the array which is being returned by fetch_assoc, which is pointless. My function can be used if you want to add conditions in the future, or manipulate some data. Otherwise, don't use a function and just use the results from fetch_assoc.

How can i get Array values to separate php variables

I am trying to retrieve records in MySQL DB.I want to retrieve all the records belong to the img_path column.from the following code I am getting results as an array.but iw ant them as separate variables.
My code
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = array(
'img_path' => $row['img_path'],
);
}
print_r($productitems);
Current Output
Array (
[0] => Array ( [img_path] => img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png )
[1] => Array ( [img_path] => img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg )
[2] => Array ( [img_path] => img ) )
expected output
$variable1 = img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png;
$variable2 = img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg;
You can use extract function like this:
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = $row['img_path'];
}
extract($productitems, EXTR_PREFIX_ALL, "variable");
echo $variable_0;
echo $variable_1;
echo $variable_2;
You can do that :
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $k => $row) {
$varName = 'var' . $k;
$$varName = array(
'img_path' => $row['img_path'],
);
}
And you will have access to $var0, $var1, and so forth.
You might use, extract() function. Docs here
The extract() function imports variables into the local symbol table
from an array.
This function uses array keys as variable names and values as variable
values. For each element it will create a variable in the current
symbol table.
This function returns the number of variables extracted on success.
Use list().
http://php.net/manual/en/function.list.php
From the manual:
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
You can also use the following code, where you do not need to use an additional function like list() or extract(). It is also a very minimalistic approach.
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $key => $row) {
${'img_path_'.$key} = $row['img_path'];
}
/*
Output:
["img_path_0"]=>
string(50) "img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png"
["img_path_1"]=>
string(50) "img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg"
["img_path_2"]=>
string(3) "img"
*/

PhP compare two arrays then write to file

I have inbound return data -> http://php.net/manual/en/function.json-decode.php that is in PhP array format. The file data is the same type. It is just $result from the previous cycle.
$result = api_query("mytrades", array("marketid" => $id));
How do I compare $result array with $file array and then over write FILE with $result data?
In other words, FILE and the data it contains is continuously being updated with $result
compare -> overwrite -> repeat at next execution.
I tried array_diff but it does not like my data types and I cannot find a work around.
Note: .db file is empty at first cycle but becomes populated at first write.
sample code with Array to string conversion error:
<?php
$id = 155;
require_once('phpPlay.php');
$result = api_query("mytrades", array("marketid" => $id));
$lines = file("myDB.db");
$arrayDiffresult = array_diff ( $result, $lines);
var_dump($result);
file_put_contents('myDB.db', print_r($result, true));
?>
var_dump($result);
I think, you looking for some serialization, json_encoding for example.
$result = array(
'return' => array(
array(
"tradeid" =>"74038377",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"197009493",
),
array(
"tradeid" =>"2",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"2",
)
)
);
function getdiff($new, $old)
{
//implement right logical diff here
$diff = array();
$old_serialized = array();
foreach ($old as $item) {
$old_serialized[] = json_encode($item);
}
foreach ($new as $item) {
if (in_array(json_encode($item), $old_serialized)) {
continue;
}
$diff[] = $item;
}
return $diff;
}
$old = file_exists('1.db') ? json_decode(file_get_contents('1.db'), 1) : array();
$arrayDiffresult = getdiff($result['return'], $old);
file_put_contents('1.db', json_encode($result['return']));
print_r($arrayDiffresult);

change key names in array in php

ok..I'm trying to re-map the keynames of a key-value array in php using a fieldmap array ie.
i want the $outRow array to hold $inRow['name1'] = 10 to $outRow['name_1'] = 10 for a large set of pre-mapped values..
$fieldmap=array("name1"=>"name_1","name2"=>"name_2");
private function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[$this->fieldmap[$key]][] = $value;
}
return $outRow;
} // end mapRow
public function getListings($inSql) {
// get data from new table
$result = mysql_query($inSql);
if (!result) {
throw new exception("retsTranslate SQL Error: $inSql");
}
while ($row = mysql_fetch_assoc($result)) {
$outResult[] = $this->mapRow($row);
}
return $outResult;
} // end getListings
this is not working..I'm getting the array but its using $outResult[0][keyname]...I hope this is clear enough :)
$fieldmap=array("name1"=>"name_1","name2"=>"name_2");
private function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[$this->fieldmap[$key]][] = $value;
}
return $outRow;
} // end mapRow
while ($row = mysql_fetch_assoc($result)) {
//$outResult[] = $this->mapRow($row);
$outResult[= $this->mapRow($row);
}
I commented your line of code and added new one..it definitely got what you mentioned in question.
If you can structure your arrays to where the keys align with the values (see example below) you can use PHP array_combine(). Just know that you will need to make absolutely sure the array is ordered correctly.
<?php
$fieldmap = array( 'name_1', 'name_2', 'name_3' );
private function mapRow($inRow)
{
$outRow = array_combine( $this->fieldmap, $inRow );
return $outRow;
}
For example, if your array was:
array( 'name1' => 10, 'name2' => 20, 'name3' => 30 );
The new result would be:
array( 'name_1' => 10, 'name_2' => 20, 'name_3' => 30 );
Let me know if this helps.
Try this:
function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[preg_replace('/\d/', '_$0', $key,1)] = $value;
}
return $outRow;
}

How to access array computer by a function within Codeigniter?

I have a function as follow:
function get_employee_information()
{
$this->db
->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
}
I'm trying to access this data from within an output to template, like this:
$this->get_employee_information();
$output = $this->template->write_view('main', 'records', array(
'employee_names' => $employee_names,
'employee_ids' => $employee_ids,
), false);
Yet this isn't displaying anything. I feel like this is something small and I should know better. When I tun print_r($arrayname) on either array WITHIN the function, I get the suspected array values. When I print_r OUTSIDE of the function, it returns nothing.
Your function is not returning anything. Add the return shown below.
function get_employee_information()
{
$this->db->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
return array(
'employee_names'=>$employee_names,
'employee_ids'=>$employee_ids,
);
}
You are not setting the return value of the function to a variable
$employee_info = $this->get_employee_information();
$output =
$this->template->write_view(
'main', 'records',
array(
'employee_names' => $employee_info['employee_names'],
'employee_ids' => $employee_info['employee_ids'],
),
false
);

Categories