Insert two associative arrays with foreach loop in codeigniter - php

I am trying to insert two arrays (associative) with foreach loop in codeigniter
$senti = $this->input->post('field_id');
$options = $this->input->post('field');
$i=0;
foreach( $options as $option and $senti as $sen )
{
$insert_option = array
(
'form_id' => $token,
'name' => $this->db->escape_str($option['name']),
'fillup_id' => $rand,
'field_id' => $this->db->escape_str($sen['id'])
);
$this->db->insert('form_value', $insert_option);
$i++;
}
But I get error with the above code.
On the other hand if I use foreach( $options as $option) then I get the entries for $option['name'] but not for $sen['id'].
Also if this could be done with any other loop I am happy to learn.

It's not possible to loop through two arrays ($senti and $options) at the same time with foreach.
You have to find a way to merge the two arrays. Below is an example with while, but it will skip the values of the longest array. I don't know the data structure you're using so I don't know if that's a problem.
Every iteration while checks if the key $i exists in the array. When the key exists in both arrays it will progress. With $i++ the variable is incremented by 1 and the loop can start over again.
$senti = $this->input->post('field_id');
$options = $this->input->post('field');
$i = 0;
while(isset($options[$i]) && isset($senti[$i])) {
$insert_option = array
(
'form_id' => $token,
'name' => $this->db->escape_str($options[$i]['name']),
'fillup_id' => $rand,
'field_id' => $this->db->escape_str($senti[$i]['id'])
);
$this->db->insert('form_value', $insert_option);
$i++;
}

Related

Create Array Inside Foreach Loop

How to put these codes in a foreach loop?
$item1_details = array(
'id' => 'a1',
'price' => 18000,
'quantity' => 3,
'name' => "Apple"
);
$item2_details = array(
'id' => 'a2',
'price' => 20000,
'quantity' => 2,
'name' => "Orange"
);
Then the array above will be saved in a variable. It's an array. And, yes, I have no idea how to do a loop inside array. So please help me for this too.
$item_details = array ($item1_details, $item2_details);
Thus, I have to questions. First, how to create an array inside a foreach loop. Second, How to loop inside an array.
You don't put a loop inside an array, you push onto the array in a loop.
$item_details = array();
for ($i = 0; $i < 10; $i++) {
$item_details[] = $item1_details;
$item_details[] = $item2_details;
}
This will make an array with 10 alternating copies of $item1_details and $item2_details.
You mentioned a foreach loop, but that's for looping over an array that already exists. You didn't show any array to loop over, so I'm not sure how it applies in this case.
You can use array_values with array_merge
$f = array_merge(array_values($item1_details), array_values($item2_details));
Working example :- https://3v4l.org/fDM3N

PHP calculate array data

I am having trouble to calculate the sum of an array values
my array is
$bar_chart_data =
array(
array(
array("Data1",548.25),
array("Data2",238.75),
array("Data3",95.50),
array("Data4",300.50),
array("Data5",286.80),
array("Data6",148.25)
)
);
I am using this php code to calculate the results but its always gives me 0
$sumArray = array();
foreach ($bar_chart_data as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$id]+=$value;
}
}
print_r($sumArray);
Your $id is different in all iteration.
You have to use $sumArray[$k]+=$value[1];.
You also have to init $sumArray[$k] to 0 between your two foreach.
I believe you have an array containing a sub-array and you want to get the sum of all the values in each of the sub-arrays.
I suggest you use an associative sub-array to make the task easier.
$bar_chart_data = array(
array(
"Data1" => 548.25,
"Data2" => 238.75,
"Data3" => 95.50,
"Data4" => 300.50,
"Data5" => 286.80,
"Data6" => 148.25
),
array(
)
);
$sumArray = array(); // Create an empty array to store the sum of each sub-array
foreach ($bar_chart_data as $subArray) {
$sum = 0; // Initialize sum as zero
foreach ($subArray as $key=>$value) {
$sum += $value;
}
$sumArray[] = $sum; // Append each sum to the array
}
print_r($sumArray); // Print the array containing the sums.
You only need one loop, then extract the values at index 1 and sum them:
foreach($bar_chart_data as $values) {
$sumArray[] = array_sum(array_column($values, 1));
}
You can add the $k => $values back and use $sumArray[$k] if needed, but the way your array is shown it will work without it.

create nested array from string with delimiter

I has a string like as brachA-branchB-branchC. I am trying to make it as nested array as follows
[
'name'=>'brachA',
'sub'=> [
'name'=>'brachB',
'sub'=>[
'name'=>'brachC'
]
]
]
I tried as follows (https://3v4l.org/A781D)
<?php
$nested_array = array();
$temp = &$nested_array;
$item = 'brachA-branchB-branchC';
foreach (explode('-', $item) as $key => $value) {
$temp = &$temp[$value];
}
print_r($nested_array);
Output I am getting as follows
Array
(
[brachA] => Array
(
[branchB] => Array
(
[branchC] =>
)
)
)
Any idea, how to achieve this ?
It can probably be done using a foreach loop over the reversed array returned by explode() but it is much easier to use a recursive function.
function makeArray(array $pieces)
{
$first = array_shift($pieces);
$array = array('name' => $first);
if (count($pieces)) {
$array['sub'] = makeArray($pieces);
}
return $array;
}
$item = 'brachA-branchB-branchC';
print_r(makeArray(explode('-', $item)));
The makeArray() function receives an array with the string pieces. It puts the first item under the 'name' key of a new array and invokes itself with the rest of the array to generate the array to put under the 'sub' key. It doesn't put anything for the 'sub' key if there is no rest (on the last call, $pieces is array('brachC').

A couple of issues with PHP arrays

Here is how my code is supposed to work. I pull data from a few remote JSON urls and decode them back into normal arrays. Then I loop through those arrays and create a single combined array. While looping I do an array_search inside the combined array to see if the value for username already exists and return the key. If a key is returned then I combine the data from that key with the loops data. If the search returns false then I add the loop data to the end of the array.
There are a couple issues I am having and they could be related but I am not sure.
First, in my code when my array_search is ran it breaks the code.
Second, if I var_dump the master array above the array_search if statement then the array is populated with the first round of the loop, however when I look at the structure of the array from the dump I see that the array starts out strange and I don't know why.
Here is the code
$master_user_array = array();
foreach($url_list AS $url) {
$json = file_get_contents($url."?key=".self::AUTH_KEY);
$data = json_decode($json, true);
$user_count = 0;
foreach($data['user'] AS $user) {echo highlight_string(var_export($master_user_array, true));
if(count($master_user_array) > 0) {
$key = array_search($user['username'], array_column($master_user_array, 'username'));
} else {
$key = false;
}
if(false !== $key) {
$master_user_array[$key]['username'] = $user['username'];
$master_user_array[$key]['email'] = $user['email'];
$master_user_array[$key]['total']['counttoday'] += $user['counttoday'];
$master_user_array[$key]['total']['countweek'] += $user['countweek'];
$master_user_array[$key]['total']['countmonth'] += $user['countmonth'];
$master_user_array[$key]['total']['countyear'] += $user['countyear'];
$master_user_array[$key]['total']['counttotal'] += $user['counttotal'];
$master_user_array[$key]['sites'][$data['siteurl']]['counttoday'] = $user['counttoday'];
$master_user_array[$key]['sites'][$data['siteurl']]['countweek'] = $user['countweek'];
$master_user_array[$key]['sites'][$data['siteurl']]['countmonth'] = $user['countmonth'];
$master_user_array[$key]['sites'][$data['siteurl']]['countyear'] = $user['countyear'];
$master_user_array[$key]['sites'][$data['siteurl']]['counttotal'] = $user['counttotal'];
} else {
$master_user_array[$user_count]['username'] = $user['username'];
$master_user_array[$user_count]['email'] = $user['email'];
$master_user_array[$user_count]['total']['counttoday'] = $user['counttoday'];
$master_user_array[$user_count]['total']['countweek'] = $user['countweek'];
$master_user_array[$user_count]['total']['countmonth'] = $user['countmonth'];
$master_user_array[$user_count]['total']['countyear'] = $user['countyear'];
$master_user_array[$user_count]['total']['counttotal'] = $user['counttotal'];
$master_user_array[$user_count]['sites'][$data['siteurl']]['counttoday'] = $user['counttoday'];
$master_user_array[$user_count]['sites'][$data['siteurl']]['countweek'] = $user['countweek'];
$master_user_array[$user_count]['sites'][$data['siteurl']]['countmonth'] = $user['countmonth'];
$master_user_array[$user_count]['sites'][$data['siteurl']]['countyear'] = $user['countyear'];
$master_user_array[$user_count]['sites'][$data['siteurl']]['counttotal'] = $user['counttotal'];
$user_count++;
}
}
}
And here is the output from the var_dump notice the array starts with array (
) 1. If I get rid of the array_search and the code doesn't break then this part of the array is added to the beginning of every round of the loop. Always with a 1.
array (
) 1 array (
'' =>
array (
'username' => 'somename',
'email' => 'someemail',
'total' =>
array (
'counttoday' => 0,
'countweek' => 0,
'countmonth' => 0,
'countyear' => 0,
'counttotal' => 3,
),
'sites' =>
array (
'' =>
array (
'counttoday' => 0,
'countweek' => 0,
'countmonth' => 0,
'countyear' => 0,
'counttotal' => '3',
),
),
),
)
Just so everyone knows I went a different way. Rather than trying to make things so complicated I was able to simplify the array and get rid of the array_search altogether.

Loop through a multi dimensional array checking a specific key for repeat values in PHP

I have a multi dimensional array that I have got from a database and I want to check this array for duplicate data and store it in another array of duplicates. my code is as follows
//create temp array
$tmp = array();
foreach ($matchingarray as $nameKey => $match) {
// loop through and stoe the contents of that array to another so i can compare
$tmp[] = $match;
}
// create an array to store duplicates
$duplicatesArray = array();
// if the temp array is not empty then loop through both arrays
if (! empty($tmp)) {
foreach ($tmp as $key => $tmpvalue) {
foreach ($matchingarray as $key => $match) {
// if a key name is the same in both arrays then add it tothe duplicates array
if ($tmpvalue['name'] == $match['name']) {
$duplicatesArray = $match;
}
}
}
}
//count how many are duplicates
$dups = count($duplicatesArray);
What I would like to know is this the right logic?
I will take where Igoel left off
there is 1 error and also 1 suggest that i will make.
Error:
you cannot reuse $key twice in the foreach because they will override.
Suggestion as what Igoel stated: your best bet for duplicate effectively is to use sql. SQL is faster at processing than looping through arrays. Don't forget you need to load the data into memory and thats costly.
Try this way
<?php
static $cnt = array();
$min = 1;
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k){
global $cnt;
$cnt[] = $v;
}
array_walk_recursive($coll, 'recursive_search');
$newNumbers = array_filter(
array_count_values($cnt),
function ($value) use($min) {
return ($value > $min);
}
);
echo "Values > 1 are repeated \n";
print_r(array_count_values($cnt));
echo "Values repeted\n";
print_r($newNumbers);
DEMO

Categories