Insert key value - array in array - php

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

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

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

Why my php array is over written when they have same Keys

I have a custom PHP function which executes a stored procedure and returns an array:
function test(){
$in = array("abc","bcd","efg");
$result = mydba->executestoredprocedure('proc1',$in);
$arr_sim = array();
foreach ($result['recordset'] as $rows) {
if (!empty($rows)) {
echo $arr_sim[$rows['field1']] = $rows['field2'];
}
}
return $arr_sim;
}
In the above function $arr_sim is returning the number of items correctly when the rows["field1"] values are different. If the rows["field1"] values are the same then it is overwriting the first value and returning only the last one. How can I overcome this?
array ( [chicago] => 'sears', [rochester] => 'liberty' )
If the $arr_sim contains these items then it is returned correctly. Because the keys are different.
array ( [chicago] => 'MCD', [chicago] => 'TACOBELL' )
If the $arr_sim contains these items then it is not returned correctly. Because the keys are the same, "chicago".
Array keys must be unique. Instead, do something like this:
// You want the array to look like this
// array('chicago' => array('MCD', 'TACOBELL'));
function test(){
$in = array("abc","bcd","efg");
$result = mydba->executestoredprocedure('proc1',$in);
$arr_sim=array();
foreach ($result['recordset'] as $rows) {
if(!empty($rows)){
if(array_key_exists($rows['field1'], $arr_sim) {
$arr_sim[$rows['field1']][] = $rows['field2'];
} else {
$arr_sim[$rows['field1']] = array($rows['field2']);
}
}
}
return $arr_sim;
}
Replace $arr_sim[$rows['field1']] = $rows['field2'] with $arr_sim[$rows['field1']][] = $rows['field2']. This will create an array of arrays.
echo $arr_sim['chicago'][0]; // MCD
echo $arr_sim['chicago'][1]; // TACOBELL
Technically, you should write something like this to avoid notices:
if (!isset($arr_sim[$rows['field1']])) $arr_sim[$rows['field1']] = array();
$arr_sim[$rows['field1']][] = $rows['field2'];
But you must really ask yourself, is the field1 (city names) worthy of being the primary key for the array? If not, you should choose some other identifier.

How can I create an array with key value pairs?

How can I add key value pairs to an array?
This won't work:
public function getCategorieenAsArray(){
$catList = array();
$query = "SELECT DISTINCT datasource_id, title FROM table";
if ($rs=C_DB::fetchRecordset($query)) {
while ($row=C_DB::fetchRow($rs)) {
if(!empty($row["title"])){
array_push($catList, $row["datasource_id"] ."=>". $row["title"] );
}
}
}
return($catList);
}
Because it gives me:
Array ( [0] => 1=>Categorie 1 [1] => 5=>Categorie 2 [2] => 2=>Caterorie 2 )
And I expect:
Array ( [1] =>Categorie 1 [5] => Categorie 2 )
$data =array();
$data['user_code'] = 'JOY' ;
$data['user_name'] = 'JOY' ;
$data['user_email'] = 'joy#cargomar.org';
Use the square bracket syntax:
if (!empty($row["title"])) {
$catList[$row["datasource_id"]] = $row["title"];
}
$row["datasource_id"] is the key for where the value of $row["title"] is stored in.
My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:
$catList[$row["datasource_id"]] = $row["title"];
In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.
You can create the single value array key-value as
$new_row = array($row["datasource_id"]=>$row["title"]);
inside while loop, and then use array_merge function in loop to combine the each new $new_row array.
You can use this function in your application to add keys to indexed array.
public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
$resArr = array();
foreach ($indexedArr as $item)
{
$tmpArr = array();
foreach ($item as $key=>$value)
{
$tmpArr[$keys[$key]] = $value;
}
$resArr[] = $tmpArr;
}
return $resArr;
}
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}

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