Adding to a multidimensional array in PHP - php

I have an array being returned from the database that looks like so:
$data = array(201 => array('description' => blah, 'hours' => 0),
222 => array('description' => feh, 'hours' => 0);
In the next bit of code, I'm using a foreach and checking the for the key in another table. If the next query returns data, I want to update the 'hours' value in that key's array with a new hours value:
foreach ($data as $row => $value){
$query = $db->query('SELECT * FROM t WHERE id=$row');
if ($result){
$value['hours'] = $result['hours'];
}
It's all fine except that I've tried just about every combination of declarations for the foreach loop, but I keep getting the error that the $value['hours'] is an invalid reference. I've tried declaring $value[] ... but that doesn't work either. I don't need to iterate through $value so another foreach loop isn't necessary.
Surely this is easier than my brain is perceiving it.
Here's the whole snippet:
foreach($_gspec as $key => $value){
$sql = sprintf('SELECT * FROM List WHERE specialtyID=%s', $key);
$query = $db->query($sql);
if ($query->num_rows() !== 0){
$result = $query->row_array();
$value['hours'] = $result['hours'];
}
}

You want
$data[$row]['hours'] = $result['hours']
$row would be better named as $key (that is what it is!)
Some people would suggest using pointers, but I find this way makes more sense to me.

You need to use ampersand in front of the $value in foreach to pass it by reference like this:
foreach ($data as $row => &$value){
$query = $db->query($sql);
if ($result){
$value['hours'] = $result['hours'];
}
}
More info here: http://php.net/manual/en/control-structures.foreach.php
As of PHP 5, you can easily modify
array's elements by preceding $value
with &. This will assign reference
instead of copying the value.

Use reference ->
foreach ($data as $row => & $value) {
$query = $db->query('SELECT * FROM t WHERE id=$row');
// [...]
if ($result) {
$value['hours'] = $result['hours'];
}
}

Related

How to loop this array and save to database?

I have this array to save to database:
{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}
how do I save it to DB so the databse should be like this.
i_barcode_id i_barcode_sn
3 8999999565404
3 6933412700043
this is my current script.
foreach($myarray as $row){
$dataadd_sto_d = array (
'ID' => $rows['i_barcode_id'],
'SN' => $rows['i_barcode_sn']
);
$insertsto_d = $this->MWarehouse->add_sto_d($dataadd_sto_d); //insert script
};
The script failed to save to database. I do not know why. any
Use this tested working
$key = array();
$value = array();
foreach($myarray as $row){
$id => $rows['i_barcode_id'],
$sn => $rows['i_barcode_sn']
array_push($key, $id);
array_push($value, $sn);
}
$insert_data = array_combine($key, $value);
return $this->MWarehouse->add_sto_d($insert_data);
Note
array_combine() will now throw a ValueError if the numberof elements for each array is not equal; previously this function returned false instead.
You have some typos in your Code like foreach(... as $row) and later you want to access $rows
My Attemp would be, to grap i_barcode_id or i_barcode_sn to loop and take the value index to get the data from the other array.
Example:
//true at the end, cause i have something against stdClass without any reason
$myarray = json_decode('{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}',true);
foreach($myarray['i_barcode_id'] as $key => $val){
$insertArray=array(
"ID" => $val,
"SN"=>$myarray['i_barcode_sn'][$key]
);
//Your Insert Script
};

foreach array wise multi SQL query not working in PHP

I am trying to execute multiple queries with the multiple selected checkbox value-wise in PHP.
I am facing trouble that my code is executing only one checkbox value-wise query and the rest is denied.
I checked on StackOverflow about this issue and I got lots of threads about foreach loop but in my case, it is not working when I am applying that.
Please help me, I am first time trying the foreach loop and so that I have a bit confusing about the same.
I have also the problem that I am not able not to validate invalid data through an array.
How I fix this? it only works for the first check value but I want all checked checkboxes.
I am trying to fetch data from the database of those particular ids which value I selected in the checkbox. and echo it in the array for that all query as I mention below-
Sending Form Data format as seen in dev tool
referenceID[]: PO0203211
referenceID[]: PO203213
PHP
$checkbox = $_POST['referenceID'];
foreach ($checkbox as $chk) {
$stmt = $con->prepare(
"SELECT * FROM `table` WHERE `ref` = :referenceid"
);
$stmt->execute([':referenceid' => $chk]);
$stmt = $stmt->fetchAll();
$response = [];
$i = 1;
foreach ($stmt as $data) {
$response[] = [
"slno" => $i,
"name" => $data['name'],
"orderid" => $data['address'],
];
$i++;
}
echo json_encode($response);
exit();
}
Try this, when using exit() inside the foreach the code does not continue and only performs the first element.
EDIT 1:
Ok, I'm going to explain a little more in depth how to optimize this code.
You get "id" identifiers from checked checkboxes.
You can use SQL IN () to optimize this.
Look at this
$checkboxDivide = implode("','", $_POST['referenceID']);
$response = []; //Final Result
$stmt = [];
$query = mysqli_query($con,
"SELECT * FROM `table` WHERE `ref` IN('{$checkboxDivide}')"
);
while($stmt[] = mysqli_fetch_assoc($query));
//Delete empty last array
array_pop($stmt);
$i = 1;
foreach ($stmt as $data) {
$response[] = [
"slno" => $i,
"name" => $data['name'],
"orderid" => $data['address'],
];
$i++;
}
echo json_encode($response);
You're using the exit() function withing your foreach, which will terminate the current script. See php manual on exit.
I am referencing to the
foreach ($checkbox as $chk) {}
not to the
foreach ($stmt as $data) {}
The script will terminate after the first loop of the first foreach.
Try moving it out of the foreach.
**Updated answer because of the comment from #El_vanja
Move your $response = []; array above and out of the foreach loop. This will keep the data in the array and not reset the array every iteration of the foreach loop.

How to using implode from looping table in PHP?

I get error
Array to string conversion
when to implode looping from table
$sql = $this->db->query('select * from TEST');
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
//This is I'm get data from other database server(SQL server) where in 'id' from database test(local database)
//and result query i will save to table test3(database server local)
$query = $db2->query("SELECT * FROM test2 WHERE id IN($val)");
$result = array();
foreach($query->result_array() AS $row){
$result[] = array (
'id' => $row['id'],
'nm' => $row['nm'],
'golcust' => $row['golcust'],
'golcustbi' => $row['golcustbi'],
'jnsbh' => $row['jnsbh']
);
}
$this->db->insert_batch('test3',$result);
How can I fix it?
i get error
Error Number: 37000
[Microsoft][ODBC SQL Server Driver][SQL Server]Error converting data type varchar to numeric.
SELECT * FROM test3 WHERE id IN(1,2,3,4)
Filename: D:/xampp/htdocs/sipdn/system/database/DB_driver.php
Line Number: 691
I think you are not seeing that when you do this:
$array[] = array('id' => $row->id);
You are assigning an array, inside another array, and the implode function is expecting an array of values, and not an array of array with values.
The answer is that you should do this
foreach ($sql->result() AS $row){
$array = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
Instead of this
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
And the reason is that implode function firm is
string implode ( string $glue , array $strings )
Hope it helps!
try this, the simple code without implode and array
$sql = $this->db->query('select * from TEST');
$val = '';
foreach ($sql->result() AS $row){
$val .= $row->id.',';
}
// before rtrim $val is 1,2,3,
$val = rtrim($val,',');
// after rtrim $val is 1,2,3
$query = $this->db->query("SELECT * FROM TEST WHERE id IN('".$val."')");
// finally query will be "SELECT * FROM TEST WHERE id IN('1,2,3')"
may it can help you
You are setting an array inside an array. $array[] = means create a new key in $array and put everything after the equal sign into that key. So you don't have to create a new array.
It is simple as this $array[] = $row->id.
Then $array[0] would be the first id that is in the database and so on.
The problem solved I'm using query like bellow. Thanks all for response.
$sql = $this->db->query('select * from TEST');
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
}
$query = $db2->query("SELECT * FROM mCIF WHERE nocif IN ('".implode("','",$array)."')");
$result = array();
foreach($query->result_array() AS $row){
$result[] = array (
'id' => $row['id'],
'nm' => $row['nm'],
'golcust' => $row['golcust'],
'golcustbi' => $row['golcustbi'],
'jnsbh' => $row['jnsbh']
);
}
$this->db->insert_batch('test3',$result);

Return MySQL rows in array

I've been working on a OOP method that is supposed to return the rows of a MySQL query. I have to have the data array in the format:
$rows = array('row'=> rownum, 'fld1'=> fldval .... 'fldn' => fldval);
What I have encountered are the two problems of either:
returns
$rows = array('0'=>fldval, 'fld1'=> fldval .... 'n'=> fldval, 'fldn' => fldval);
or single row of
$rows = array('fld1'=> fldval .... 'fldn' => fldval);
Little frustrated as every PHP mysql function I have tried has some sort to goofy crap flaw and will not do a straight out process.
I assume there is a good example somewhere, that can get me past the crap limitations, but haven't found anything useful yet!
I've tried all of the following:
$row = mysql_result($db_res,$n);
$row = mysql_fetch_array($db_res);
$row = mysql_fetch_assoc($db_res);
$row = mysql_fetch_object($db_res);
$row = mysql_fetch_row($db_res);
None have worked successfully! For getting out the bogus "numeric" array entries. I wrote:
foreach ($row as $k => $v)
if (is_numeric($k)) { continue; }
$result[$k] = $v;
} // end foreach $row
$row = array_push($row, 'row'=>$rownum, $result);
Hoping someone has a link.
$list = array();
$query = "SELECT value FROM table";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
$list['fld' . (1 + count($list))] = $row['value'];
}
$list = array('row' => count($list)) + $list;
if table have 3 row, the code above is going to give you a array like:
array(
'row' => 3,
'fld1' => 12,
'fld2' => 34,
'fld3' => 56
);

php arrays. How to format for my result

I am pretty new to php and could sure use some help understanding how to get my result the way I need it from a database query.
What I need is an associative array like this, 'bla'=>'bla'. What I am getting from my foreach loop is this from a print:
[0] => Array
(
[0] => test0
[name] => test0
[1] => 1
[customer_id] => 1
)
[1] => Array
(
[0] => test
[name] => test
[1] => 2
[customer_id] => 2
)
Here is my loop:
foreach($res as $key=>$val)
{
// have no idea..
}
Can someone please help me to format my results so that they are like 'index'=>'value'
Thanks for any help.
Here is a sample code that uses a foreach but yet pulls an association. I don't get it. I am thinking that my result set with the indexes are because I am not writing the loop correctly. Here is the code that uses the foreach
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
Here is the part of the database class that I am using to fetch the results.
$returnArray = array();
$i=0;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
if($row)
$returnArray[$i++] = $row;
}
mysql_free_result($result);
return $returnArray;
After using the code that was given to me to omit the index numbers, here is what I am now left with. Its close but not what I need.
Array
(
[id] => 1
[cust] => bobs auto
)
This is what the above line should read like
'1' => 'bobs auto'
What I am trying to do is to format the output for a JSON call for a suggestion box.
I cannot get this to work. Here is everything after my db connection.
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
$out[$key['id']] = $val['cust'];
}
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out_array as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
OK, I think I am coming down to the home stretch. I have what I need sort of. This is the code I have so far.
$out_array = array();
foreach($items as $key)
{
$out_array[$key] = $val;
//$out_array[$key['id']] = $key['cust'];
}
Notice that the commented line does not work, It outputs like the id twice but the line that isn't commented out works just fine. Here is the output from that.
Array
(
[8] =>
[FAT BURGER] =>
)
From this point, would I just use another foreach to iterate over the entire set of data? The array output you see above is from a print_r.
This is what I now have and it returns the correct association however, I must comment out the strpos condition to get any results back and I don't know why. Am I correct in nesting these foreach loops like I have?
$out_array = array();
foreach($items as $key)
{
// $out_array[$key] = $val;
$out_array[$key['id']] = $key['cust'];
foreach ($out_array as $key=>$value)
{
if (strpos(strtolower($key), $q) !== false)
{
echo "$key|$value\n";
}
}
}
So you don't want the numeric indexes in your array? You must be using mysql_fetch_array(), which returns your results with both numeric and string keys. Use mysql_fetch_assoc() to get an array with only the string keys (the string being the column name).
Try something like this. It works by skipping the integer indices, and putting the non-integer indices into an output array.
$out_array = array();
foreach($res as $key=>$val) {
if(is_int($key)) {continue;}
$out_array[$key] = $val;
}
EDIT:
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
}
$out[$out_array['id']] = $out_array['cust'];
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
Assuming this is a MySQL database, the results, if more than one, are returned as a multidimensional array.
When you run the query:
$query = "SELECT * FROM Table WHERE ...";
$query = mysql_query($query);
while($info = mysql_fetch_assoc($query)){
//$info is now a single row, associative array
echo print_r($info);
}
the echo print_r displays the results the way you are looking for them now 'index'=>'value'
EDIT: based on comments.
If you absolutely CAN'T get rid of the mysql_fetch_array then you'll have to hack the code. It's not clean and I strongly advise refactoring but below is the code you'll need to create an array of field name indexes only from what you're given
$my_array = array();
$info = $data[0]; //grab the first row of your data set from the original question.
foreach($info as $index => $value){
if(!is_int($index)){
$my_array[$index] = $value;
}
}
The newly created $my_array will be in the format you're looking for.
You got this array from a query and result function from PHP, yeah?
If you were using mysql, it's actually easier to do it like below.
$query = mysql_query("SELECT * FROM dbname"); //Create the query to your database
while($data = mysql_fetch_array($query)) //Loop through our results from the query
{
echo($data['fieldname']."<br/>"); //echo out data through the loop
}
$ret = array();
foreach($rows as $row)
{
$ret[$row['id']] = $row['cust'];
}
$json = json_encode($ret);
echo $json;
// Prints something like:
//
// {1:'bob'}
Note the use of json_encode.
Ok, regarding my last question. I was incorrect in nesting the foreach loops. I also had a typo in my code. It is working, finally. Thank you to all that have helped me!

Categories