Adding elements to an associative array during a loop - php

I have this loop:
foreach ($tables as $table => $queries) {
foreach ($queries as $query) {
$insert = array($query['column'] => $query['value']);
}
The $insert associative array should be incremented of new elements each loop, so that the logical result woud be:
$insert = array($query['column'] => $query['value'], $query['column'] => $query['value'] ...etc);
I tried using $insert[] and $insert .= and $insert += but none of these give the expected result
Thanks for any help

You are looking for this
$insert[] =

To insert in array use:
$insert[] = array($query['column'] => $query['value']);

Once the array's been defined, you have to use
$insert[$query['column']] = $query['value']; // sample #1
to specify a new key/value pair within the $insert array.
If you use
$insert[] = array(...); // sample #2
you'll just be inserting a new child array that contains a single key/value pair.
e.g. $insert before
$insert = array(
'foo' => 'bar'
);
$insert after sample #1
$insert = array(
'foo' => 'bar',
'baz' => 'qux'
);
$insert after sample #2:
$insert = array(
'foo' => 'bar'
0 => array(
'baz' => 'qux'
)
);

$insert = array();
foreach ($tables as $table => $queries)
{
foreach ($queries as $query)
{
$insert[$query['column']] = $query['value'];
}
}

Related

ForEach loop inside associative array PHP

I have following foreach loop
$selectedids = "1255;1256;1257";
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$output1 = $idstand++;
echo "<li>product_id_$output1 = $item,</li>";
}
I want to add the output of the above loop inside following associative array
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge
)
So that the final array will look like this;
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge,
'product1_id' => 1255,
'product2_id' => 1256,
'product3_id' => 1257,
)
I tried creating following solution but its not working for me
$selectedids = $boughtitem;
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$idoutput1 = $idstand++;
$paramas [] = array (
'product$idoutput1_id' => $item,
);
}
Need advice.
You don't need to define a new array, just set the key of the current array to the value you want, in the form of $array[$key] = $value to get an array that looks like [$key=>$value], or in your case...
$paramas['product' . $idoutput1 . '_id'] = $item;

Parse php array to make insert statement

Hi I have an array like this:
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
]
foreach($datas as $data){
//get items here...
}
How to pair or parse those items to make insert statement like this:
INSERT INTO table (name, settings)VALUES('John','Settings 1');
INSERT INTO table (name, settings)VALUES('Mickey','Settings 2');
Any idea? Thanks in advance.
This code could be usefull for creating array of arrays. Considering array keys will be name_x and settings_x
foreach($datas as $key=>$value){
// explode each key of the array
$keys = explode('_',$key);
$name = 'name_'.$keys[1];
$settings = 'settings_'.$keys[1];
// to generate array
$new_array[$keys[1]]=array('name'=>$datas[$name], 'settings'=>$datas[$settings]);
}
print_r($new_array);
Loop the $new_array for insert query.
Output :
Array
(
[1] => Array
(
[name] => John
[settings] => Settings 1
)
[2] => Array
(
[name] => Mickey
[settings] => Settings 2
)
)
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
];
$results = [];
foreach($datas as $index=>$data){
//create an array out of $index breaking it at the '_'
//so array will be $parts = [0=>'name', 1=>'1'];
$parts = explode('_', $index);
//'name_1'=>'John' = $results[1]['name'] = 'John';
$results[$parts[1]][$parts[0]] = $data;
}
//batch insert new formed array
//INSERT INTO tbl_name (name, settings) VALUES $results;
Check this, you must do some intermediate steps. Comments on code!!
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
];
$data_final = [];
foreach($datas as $key=>$value){
$keyX = preg_replace('/^(.+)_(\d+)$/', '$1', $key);// get the "type" (name, setting)
$keyY = preg_replace('/^(.+)_(\d+)$/', '$2', $key);// get the "index" (_1, _2 without "_")
$data_final[$keyY][$keyX] = $value; // put in result
}
// make queries
$sql = [];
foreach($data_final as $datas){
$fields = implode(", ", array_keys($datas)); //implode the keys to sql fields
$values = implode(", ", array_map(function($a){return "'$a'";}, array_values($datas)));//implode values to sql values adding ''. WARNING: This not escape values. Use escape string function on mysqli obj or PDO to the right escape
$sql[] = "INSERT INTO table ($fields) VALUES ($values);"; // populate query
}
$sql = implode("\n", $sql); // implode with new line
print_r($sql); //results
IMPORTANT:
You must have the right syntax "field_number" to respect the procedure
You can use even with one or more of two fields per record
You can use any field name, always respecting the "field_number" syntax
DEMO HERE

PHP - array key within array value

I have a PHP array like this:
$arr = array(
'id' => 'app.settings.value.id',
'title' => 'app.settings.value.title',
'user' => 'app.settings.value.user'
);
I want to remove '.id', '.title' and '.user' in the array values. I want to insert the key of this array at the end of the value. I know, that I can get an array key by passing an array and a value to 'array_search', but I want the key within this one array definition - at the end of it's value. Is this possible?
I don't like this, but I guess it's simple and works:
$arr = array(
'id' => 'app.settings.value',
'title' => 'app.settings.value',
'user' => 'app.settings.value'
);
$result = array();
foreach ($arr AS $key => $value) {
$result[$key] = $value . '.' . $key;
}
You're storing app.settings.value which is the same for all array items, so personally I'd prefer:
$arr = array(
'id',
'title',
'user'
);
function prepend_key($key)
{
return 'app.settings.value.' . $key;
}
$result = array_map('prepend_key', $arr);
With $result containing:
array(
'app.settings.value.id',
'app.settings.value.title',
'app.settings.value.user'
);
At the end of the day, either works :)

PHP array within array

Can someone explain to me why this isn't working? I'm trying to push an array into another array, but its only coming back with the last item from the $votes array.
foreach($json['area'] as $row) {
$name = $row['name'];
$group = $row['array']['group'];
$majority = $row['array']['majority'];
$candidates = $row['array']['candidates'];
foreach ($candidates as $candidate) {
$vote = $candidate["votes"];
$candi = $candidate["name"];
$votes = array("vote" => $vote, "candidate" => $candi);
}
$array = array("name" => $name, "group" => $group, "majority" => $majority, "votes" => $votes);
$results[] = $array;
}
Each iteration of the outer loop is only producing a single $votes array , seemingly for a single candidate, in this line:
$votes = array("vote" => $vote, "candidate" => $candi);
If you want to capture multiple entries in that array for each row, you need to make it a multi-dimensional array also:
$candidates = $row['array']['candidates'];
$votes = [];
foreach ($candidates as $candidate) {
$votes[] = array(
"vote" => $candidate["votes"],
"candidate" => $candidate["name"]
);
}
$array = array(
"name" => $name,
"group" => $group,
"majority" => $majority,
"votes" => $votes
);

Get count of each element returned by mysql query

This is my query:
SELECT `Brand`,`Colour`,`Occassion`,`Fabric`,`Type`
FROM `deals`
WHERE `Size`
LIKE '%XS%';
It returns 35 results. Now, what i want is a count of each of the columns (Brand, colour etc) which are present in the above resultset to create a histogram. I am not sure about how to do this.
Any help is appreciated.
I think ideal result should look like this:
$data = array(
"Brand" => array(brand1 => 1, brand2 => 2),
"Colour" => array(colour1 => 1, colour2 => 2),
"Occassion" => array(Occassion1 => 1, Occassion2 => 2),
);
For each subarray we can draw a histogram. The code will look like this:
$query = "
SELECT
`Brand`,`Colour`,`Occassion`,`Fabric`,`Type`
FROM
`deals`
WHERE
`Size` LIKE '%XS%'";
$data = array(
"Brand" => array(),
"Colour" => array(),
"Occassion" => array(),
"Fabric" => array(),
"Type" => array(),
);
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
foreach($row as $key => $value)
{
$data[$key][$value]++;
}
}
/* free result set */
$result->free();
}
Or we can define $data subarrays inside foreach to make the program more flexible:
$data = array();
...
foreach($row as $key => $value)
{
if(!isset($data[$key]))
{
$data[$key] = array();
}
$data[$key][$value]++;
}
...

Categories