Codeigniter- How to insert different sizes of arrays into database - php

I want to insert data in table 'projects'. I have two arrays with different sizes, they are
$advisor_id = array(
'id' =>1
'id' =>2
'id' =>3
);
$project_id = array(
'pid'=>1
'pid'=>2
'pid'=>3
'pid'=>4
);
My code is:
$advisors = count($this->input->post('advisor_id[]'));
$PM_ids = count($this->input->post('PM_id[]'));
if($advisors > $PM_ids){
$count = $advisors;
}else{
$count = $PM_ids;
}
$data[] = array();
for($i =0; $i<$count ; $i++){
$data = array(
'advisor_id' =>$this->input->post('advisor_id')[$i],
'PM_id' =>$this->input->post('PM_id')[$i],
);
//print_r($data);
$this->db->insert_batch('project_config',$data);
}
My problem is the different sizes of arrays. How can I insert into database.

If you are happy to submit NULL values where missing, array_map() is the best tool for the job.
First a general demonstration of how/where NULL elements are generated when array size mismatches occur...
Code: (Demo)
$advisor_id=['id1'=>1,'id2'=>2,'id3'=>3];
$project_id=['pid1'=>1,'pid2'=>2,'pid3'=>3,'pid4'=>4];
$data=array_map(function($id,$pid){return ['advisor_id'=>$id,'PM_id'=>$pid];},$advisor_id,$project_id);
var_export($data); // see how NULL elements are formed in the output array
Output:
array (
0 =>
array (
'advisor_id' => 1,
'PM_id' => 1,
),
1 =>
array (
'advisor_id' => 2,
'PM_id' => 2,
),
2 =>
array (
'advisor_id' => 3,
'PM_id' => 3,
),
3 =>
array (
'advisor_id' => NULL,
'PM_id' => 4,
),
)
The above multi-dimensional array is now fully prepared for a single insert_batch() call. IMPORTANT CodeIgniter's insert_batch() is specifically designed to INSERT multiple rows of data at once -- to use this call inside of a loop defeats the purpose of making this call.
As for you actual implementation, this should work (I don't code in CodeIgniter):
$data=array_map(function($id,$pid){return ['advisor_id'=>$id,'PM_id'=>$pid];},$this->input->post('advisor_id'),$this->input->post('PM_id'));
$this->db->insert_batch('project_config',$data);
CLEAN & DONE: No for loops, no $i counters, and just one call to the database.

Related

How to remove duplicate arrays from a multi dimensional array?

I have a large multidimensional array that looks like the below.
I want to remove duplicate arrays based on the ID, however, I am struggling to achieve this.
I want the duplicates to work over the entire array, so you can see that ID 1229873 is a duplicate, in the array 2021-07-07 and 2021-07-09, it should therefore be removed from 2021-07-09
How would I achieve this? array_unique has not worked for me.
$data = array (
'2021-07-07' =>
array (
0 =>
array (
'id' => 5435435,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
1 =>
array (
'id' => 1229873,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
),
'2021-07-09' =>
array (
0 =>
array (
'id' => 3243234,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
1 =>
array (
'id' => 1229873,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
),
);
This is a perfect case for array_uunique()! No wait, scratch that. The PHP devs refused to implement it for the perfectly valid reason of... [shuffles notes] "the function name looks like a typo".
[sets notes on fire]
Anyhow, you just need to iterate over that data, keep track of the IDs you've seen, and remove entries that you've already seen.
$seen = [];
foreach(array_keys($data) as $i) {
foreach(array_keys($data[$i]) as $j) {
$id = $data[$i][$j]['id'];
if( in_array($id, $seen) ) {
unset($data[$i][$j]);
} else {
$seen[] = $id;
}
}
}
I've opted for the foreach(array_keys(...) as $x) approach as avoiding PHP references is always the sane choice.
Run it.
I am Sure That is the way which you want to get the unique array.
$unique = array_map("unserialize", array_unique(array_map("serialize", $data)));
echo "<pre>";
print_r($unique);
echo "</pre>";

Inserting Array into PHP Array

Working with an array file with following structure. I know there are additional arrays that need to be inserted under each array 'color'.
$items=array (
0 =>
array (
'color' => 'category_a',
),
1 =>
array (
'book' => 'Gone With The Wind',
'movie' => 'GWTW',
'id'=> 'A100'
),
2 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'A103'
),
3 =>
array (
'color' => 'category_b',
),
4 =>
array (
'book' => 'Across The Great Dvide',
'movie' => 'ATGD',
'id'=> 'B102'
),
5 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'B103'
),
);
Once this array is created, I am using a list to loop thru to verify that each value in the list is placed in each 'color' array as follows
foreach ($controllist as $key=>$value){
foreach($items as $item){
if(in_array($value['book'],$item){
echo "PRESENT IN ARRAY"."<BR>";
}else{
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}
For simplicity my controllist looks like
Gone With The wind
Across The Great Divide
Goldfinger
Once complete I should end up with the info for Across The Great Divide inserted into 'color'=> 'category a' as the [2] with Goldfinger moving down one. In 'color'=>category_b' the first array should be Gone With The Wind. Any of the 'color' arrays could be missing an array at any position. To sum it up, need to check for the existence of a value from the list, if not present insert into the array. Other than using the foreach loops shown is there an easier way of doing this? If not how can I get the information inserted into the proper position?
Thanks
EDIT:
I believe the question may not be clear. What I need to do is check for the existence of one array in another. If the value in conrollist is not present in the array, insert an array into the array according the position in the conrollist. The inserted array will have the same structure as the others (I can take care of this part). I am having trouble determining if it exist and if not inserting it. Hope this helps
You might want to be using a for loop instead so you have a pointer on each iteration in order to determine where you are in the array.
foreach($items as $item){
for($i = 0; $i < count($controllist); $i++) {
if(in_array($controllist[$i]['book'],$item){
echo "PRESENT IN ARRAY AT POS ".$i."<BR>";
}else{
$controllist[$i]['book'] = $yourvar;
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}

CakePHP 2.4.4 How can I sort a multi-dimensional array with Hash::sort by string keys and values?

I don't understand the docs regarding the Hash 'path', so I've had no luck. I'm trying to sort each layer alphabetically:
array(
'music' => array(
'genre' => array(
(int) 0 => 'Dubstep',
(int) 1 => 'Blues',
(int) 2 => 'Classical'
),
'instrument' => array(
(int) 0 => 'Guitar (Electric)',
(int) 1 => 'Bassoon',
(int) 2 => 'Harmonica (Diatonic)'
),
'anotherLot' => array(
I need to sort the first later of arrays by key, then the second later in each by key, and the third by the values, so I imagine the two deeper layers would be done with a nested foreach.
I'm not familiar with CakePHP's Hash class, but here is a plain PHP solution:
ksort($data); // sort main array by keys
foreach ($data as &$outer)
{
ksort($outer); // sort next layer by keys
foreach($outer as &$inner)
{
asort($inner); // sort inner arrays by values
}
}

Passing an Associative array into another associative array in PHP

apologies if this is a simple fix - I'm having trouble passing a few arrays in PHP.
I have two arrays setup eg:
$person = array(
'height' => 100,
'build' => "average",
'waist' => 38,
);
$hobbies = array(
'climbing' => true,
'skiing' => false,
'waist' => 38,
);
now if I perform a print_r() on these arrays they return results as expected.I then insert the 2 arrays into a new array as seen below:
$total = array($person, $hobbies);
using print_r once again returns a new array containing both arrays but it is not associative. However if I try to do the following:
$total = array(
'person' <= $person,
'hobbies' <= $hobbies,
);
and I perform a print_r on $total using the code above I am not seeing both arrays with associations. ^ the above data is just an example data but identical in structure in my real app, I get returned the following result:
Array ( [0] => 1 [1] => 1 )
Once again apologies if I am being extremely thick - which I have a feeling I am.
It sounds like you want the $total array to have person and hobbies keys for the sub-arrays. If so, simply do this:
$total = array("person" => $person, "hobbies" => $hobbies);
Example with output: http://3v4l.org/5U5Hh
Your array assignments are the wrong way round: 'person' <= $person should be 'person' => $person.
// Wrong
$total = array(
'person' <= $person,
'hobbies' <= $hobbies,
);
// Right
$total = array(
'person' => $person,
'hobbies' => $hobbies,
);
You need to use array_merge, if you want to merge both array into a new array.
$result = array_merge($person, $hobbies);

Merging multiple multidimensional arrays

I have a variable number of multidimensional arrays but all with the same 4 possible values for each item.
For example:
Array
(
[companyid] => 1
[employeeid] => 1
[role] => "Something"
[name] => "Something"
)
but every array may have a different ammount of items inside it.
I want to turn all the arrays into one single table with lots of rows. I tried array_merge() but I end up with a table with 8, 12, 16... columns instead of more rows.
So... any ideas?
Thanks
Didn't test it, but you could try the following:
$table = array();
$columns = array('companyid' => '', 'employeeid' => '', 'role' => '', 'name' => '');
foreach($array as $item) {
$table[] = array_merge($columns, $item);
}
This should work since the documentation about array_merge say:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one.
So you either get the value of the current item or a default value that you can specify in the $columns array.
$array1=Array
(
"companyid" => 1,
"employeeid" => 4,
"role" => "Something",
"name" => "Something",
);
$array2=Array
(
"companyid" => array(2,2,2),
"employeeid" => 5,
"role" => "Something2",
"name" => "Something2"
);
$array3=Array
(
"companyid" => 3,
"employeeid" => 6,
"role" => "Something3",
"name" => "Something3"
);
//Using array_merge
$main_array["companyid"]=array_merge((array)$array1["companyid"],(array)$array2["companyid"],(array)$array3["companyid"]);
$main_array["employeeid"]=array_merge((array)$array1["employeeid"],(array)$array2["employeeid"],(array)$array3["employeeid"]);
for($i=0;$i<count($main_array["companyid"]);$i++)
echo $main_array["companyid"][$i] + "<br />";
for($i=0;$i<count($main_array["employeeid"]);$i++)
echo $main_array["employeeid"][$i] + "<br />";
I've tested the code above and seems right.
You coult also improve this code into a DRY function.

Categories