How to loop this array and save to database? - php

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
};

Related

Insert key value - array in array

I am getting some values (domain names) from a _POST which I have to insert into an "Array in an Array". The array is called $postValues["domainrenewals"] and the I need to create another array inside this one in the format:
domainname => 1 (where 1 is the number of years).n
My code:
foreach ($_POST['renewthesedomains'] as $key => $value) {
$postValues["domainrenewals"] = array($value => "1");
}
var_dump ($postData);
The var_dump shows that only the last $key -> $value pair is being inserted into $postValues["domainrenewals"]
Any help, much appreciated.
In each pass of the foreach loop you're redefining $postValues["domainrenewals"] so of course only the last one is saved... Try doing this:
$postValues["domainrenewals"] = array();
foreach ($_POST['renewthesedomains'] as $key => $value) {
$postValues["domainrenewals"][$value] = "1";
}
If you need to add another value to the array I'm assuming it's information of the domain, so you would do something like:
$postValues["domainrenewals"][$value]['your_first_value'] = "1";
// Then for your other value
$postValues["domainrenewals"][$value]['renewalpriceoverride'] = 285.00;
Try This:
$postValues = array();
$arr=array();
foreach ($_POST['renewthesedomains'] as $value) {
$arr["domainrenewals"]=$value;
$arr["no_of_years"]=1;
$postValues[] = $arr;
$arr=array();
}

PHP -convert one column in 2D array into 1D array specfying column name

I have a 2D array , which holds the result of a mysql query. here is my code
$res=$ $this->dbconnection->Query($Query);
$query_result= array();
while($colRow=mysqli_fetch_array($res))
{
$query_result[]= $colRow;
}
Now i want 1D array which contains all rows under a particular column in $query_result.
For example, the database table contains the fields Name and ID,I know , $query_result[]= $colRow['Name'] will give query results into ID. But I need all rows under Name and Id separately , such as $name= $query_result['Name'],$Id= $query_result['ID'].
Is there any easy way to accomplish this?
Since PHP 5.5.0 you can use...
$myfield_arr = array_column($query_result, 'myfield_name');
... to isolate a column from a two dimensional array.
See http://php.net/manual/en/function.array-column.php
Please try maybe
$res=$ $this->dbconnection->Query($Query);
$query_result= array();
while($colRow=mysqli_fetch_array($res))
{
if (empty($query_result))
$query_result = $colRow;
else
{
foreach ($colRow as $key=> $val)
$query_result[$key][] = $val;
}
}
After clarifying question in comments with you, solution is:
while($colRow=mysqli_fetch_array($res)){
foreach ($colRow as $key => $value) {
if(!isset($query_result[$key])) $query_result[$key]=array();
$query_result[$key][] = $value;
}
}
Use something like this:
foreach ($rows as $key => $value) {
$$key = $value;
}
Converting array of rows into array of columns:
<?php
$arr2dm = [['key1' => 'val11', 'key2' => 'val21'], ['key1' => 'val12', 'key2' => 'val22']];
foreach ($arr2dm as $arr) {
foreach ($arr as $k => $v) {
$res[$k][] = $v;
}
}
print_r($res);
http://sandbox.onlinephpfunctions.com/code/514050d07f9ed599e010ccd11e51fc18e39647fa

Build string from array omitting empty or NULL values in PHP

I am trying to build an array from a list of URL parameters to transact with a database. Basically I have several functions that do different things. (Insert, Update, etc) so depending on what it is specifically trying to do it may not need ALL columns in the database at all times.
So say I have these 5 potential parameters that might get passed: id,gr,bl,yw,re
If I am inserting a new row all 5 coulmns need some sort of value. If I am say updating the bl column then I only pass the id and bl parameters.
So I am doing this to build the query string(not actual code just example):
foreach($_GET as $key => $value) {
$key = strtolower($key);
if (preg_match($acceptedGETS,$key)) $$key = $value;
}
$table_col = array (
'p_id' => $_GET['id'],
'p_gr' => $_GET['gr'],
'p_bl' => $_GET['bl'],
'p_yw' => $_GET['yw'],
'p_re' => $_GET['re']);
$vstring = implode(',' , $table_col);
Now this works perfectly, as long as ALL variable keys have a value (or not NULL). My question is, how can I build a string from an array, but exclude the keys that don't get passed values. Right now if keys are missing values I get this for example:
URL: http://www.mysite.com/myscript.php?id=4&re=9 would get me:
4,,,,9
when I need to just get 4,9
Thanks!
Use $get = array_filter($_GET) and it will get rid of empty or null values.
Try
$vstring = "";
$acceptedGETS = array("id", "gr", "bl", "yw", "re");
$values = array();
foreach ($_GET as $key => $value)
{
$k = strtolower($key);
if (!in_array($k, $acceptedGETS))
continue;
$values[$k] = $value;
}
$vstring = implode(",", $values);
Here is another way using just filter_input_array and set of filters
$args = array(
'id' => FILTER_VALIDATE_INT,//if it is an integer
'gr' => FILTER_SANITIZE_STRIPPED,//in case it is a string
'bl' => FILTER_SANITIZE_STRIPPED,
'yw' => FILTER_SANITIZE_STRIPPED,
're' => FILTER_SANITIZE_STRIPPED,
);
//Filter array values to avoid bad data if nothing found NULL returned
$myInputs = filter_input_array(INPUT_GET, $args);
//if it is an array join it with coma
if(is_array($myInputs))
$myInputs = implode(',', $myInputs);

Adding to a multidimensional array in 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'];
}
}

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