Add an array into another array if certain indexes match php - php

I have an two arrays in php, what i would like to do is if drug_ids match, I want to add the second array as a sub array.
What I have
Array
(
[0] => Array
(
[drug_id] => 1
[drug] => Abacavir 300mg - Tabs
)
[1] => Array
(
[drug_id] => 4
[drug] => Abacavir/Lamivudine 120/60mg - FDC Tabs
)
[2] => Array
(
[drug_id] => 3
[drug] => Abacavir/Lamivudine 600/300mg - FDC Tabs
)
);
The second array with more data
Array
(
[0] => Array
(
[id] => 2
[decision_date] => 2018-08-10
[discussion] => The product is at 2.6 MOS
[recommendation] => recommendation
[drug_id] => 1
[created] => 2018-08-16 09:23:09
[user] => System Admin
)
[1] => Array
(
[id] => 3
[decision_date] => 2018-08-10
[discussion] => recommendation.
[recommendation] =>recommendation.
[drug_id] => 4
[created] => 2018-08-16 09:23:09
[user] => System Admin
)
[2] => Array
(
[id] => 4
[decision_date] => 2018-08-10
[discussion] => The product is at 6MOS.
[recommendation] =>ggfgfg.
[drug_id] => 4
[created] => 2018-08-16 09:23:09
[user] => System Admin
)
);
I would like to push the second array into the first one as decisions if drug ids match to create a final array
[0] => Array
(
[drug_id] => 4
[drug] => Abacavir/Lamivudine 120/60mg - FDC Tabs
[decisions] => Array(
[0] => Array
(
[id] => 3
[decision_date] => 2018-08-10
[discussion] => recommendation.
[recommendation] =>recommendation.
[drug_id] => 4
[created] => 2018-08-16 09:23:09
[user] => System Admin
)
[1] => Array
(
[id] => 4
[decision_date] => 2018-08-10
[discussion] => The product is at 6MOS.
[recommendation] =>ggfgfg.
[drug_id] => 4
[created] => 2018-08-16 09:23:09
[user] => System Admin
)
)
)
Any suggestions as to how this can be achieved?
What i have tried
$table_data //first array
$table_data //second array
foreach ($table_data as $mt) {
foreach ($items as $it) {
if ($it['drug_id'] == $mt['drug_id']) {
$decision['decisions'] = $it;
array_push($table_data, $decision);
}
}
}
//This does not work

There's a bug. Try the following
foreach ($table_data as &$mt) {
foreach ($items as $it) {
if ($it['drug_id'] == $mt['drug_id']) {
if (!isset($mt['decisions'])) {
$mt['decisions'] = [];
}
$mt['decisions'][] = $it;
}
}
}

Another way:
foreach ($arr1 as &$a) {
$a["decisions"] = array_filter($arr2, function ($b) use ($a) {
return $b["drug_id"] === $a["drug_id"];
});
}

I do not recommended nested loops they will do too many unnecessary iterations. Instead, because the drug_ids in the first array are unique, copy them to be the first level's keys -- this will let you swiftly associate data between the two arrays. When the loop is done, you can remove the first level keys with array_values().
Code: (Demo)
$drugs = array_column($array1, null, 'drug_id');
foreach ($array2 as $row) {
if (isset($drugs[$row['drug_id']])) {
$drugs[$row['drug_id']]['decisions'][] = $row;
}
}
var_export(array_values($drugs));

Related

How To Merge/push array into one in php

code
$result = [];
foreach ($getAllAgent as $rkey => $rvalue) {
$found = -1;
for ($i = 0; $i < count($result); $i++) {
if ($result[$i]["brokerid"] == $rvalue["brokerid"]) {
$found = $i;
$result[$i]['get_agent_details'][] = $rvalue['get_agent_details']; //here to combine
break;
}
}
// if not found, create new
if ($found == -1) {
$result[] = $rvalue;
}
results
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[id] => 3
[name] => kenang
[ic] => 932132923
[phone] => 2313123
[0] => Array
(
[id] => 4
[name] => ivan
[ic] => 32992131
[phone] => 31231
)
)
)
)
I have one set of an array, and I loop it and restructure match the data based on ID. After that I will try to merge the same data into one array, I able add into one array. But it will not combine as one. The correct result should be as below.
[get_agent_details] => Array
(
[0] => Array(
[id] => 3
[name] => kenang
[ic] => 932132923
[phone] => 2313123
),
[1] => Array
(
[id] => 4
[name] => ivan
[ic] => 32992131
[phone] => 31231
)
)
Your problem is in this line:
$result[] = $rvalue;
Consider the case where you only have one item; this will result in:
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[id] => 1
[name] => Chesney Hawkes
[ic] => 932132923
[phone] => 2313123
)
)
)
But to be consistent, you need get_agent_details to be a list of items, that happens to have one entry:
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[0] => Array
(
[id] => 1
[name] => Chesney Hawkes
[ic] => 932132923
[phone] => 2313123
)
)
)
)
So you need to re-arrange your data, for instance by writing:
$rvalue['get_agent_details'] = [0 => $rvalue['get_agent_details']];
$result[] = $rvalue;
Then, since get_agent_details will already be a list when you encounter a second matching item, your existing code in the inner loop will do the right thing:
// Add an item to the list
$result[$i]['get_agent_details'][] = $rvalue['get_agent_details'];

Transforming multidimensional arrays

As a stepping stone towards building a bit of json from which to build dependent dropdown, I'd like to transform this array...
Array
(
[0] => Array
(
[id] => 4
[project_id] => 2289
[task] => Drawing
)
[1] => Array
(
[id] => 5
[project_id] => 2289
[task] => Surveying
)
[2] => Array
(
[id] => 6
[project_id] => 2289
[task] => Meeting
)
[3] => Array
(
[id] => 1
[project_id] => 2282
[task] => Folding
)
[4] => Array
(
[id] => 2
[project_id] => 2282
[task] => Printing
)
[5] => Array
(
[id] => 3
[project_id] => 2282
[task] => Cutting
)
)
..to something like this...
Array
(
[0] = Array
(
[project_id] => 2289
[task] => Array
(
[0] => Drawing
[1] => Surveying
[2] => Meeting
)
)
[1] = Array
(
[project_id] => 2282
[task] => Array
(
[0] => Folding
[1] => Printing
[2] => Cutting
)
)
)
Using...
$newArray = array();
foreach ($array as $row)
{
$newArray[$row['project_id']][] = $row['task'];
}
...I'm able to get this...
Array
(
[2289] => Array
(
[0] => Drawing
[1] => Surveying
[2] => Meeting
)
[2282] => Array
(
[0] => Folding
[1] => Printing
[2] => Cutting
)
)
... but I've forgotten how to include the associative keys in the result
You can modify your foreach simply using a index:
$newArray = array();
$index = array();
foreach ($array as $row)
{
$found = array_search( $row['project_id'], $index );
if( $found === False )
{
$found = array_push( $newArray, array( 'project_id' => $row['project_id'] ) )-1;
$index[$found] = $row['project_id'];
}
$newArray[ $found ]['task'][] = $row['task'];
}
eval.in demo
When a new project_id key is found, it is added to $index array, so — searching for it at next loop — I can retrieve the index of corresponding multi-dimensional array.
Just assign them as you would like, the project id in an index, and task continually pushing it there:
$newArray = array();
foreach ($array as $row) {
$newArray[$row['project_id']]['project_id'] = $row['project_id'];
$newArray[$row['project_id']]['task'][] = $row['task'];
}
$newArray = array_values($newArray); // reindex
// removes `$row['project_id']` on each group
Note: Just use array_values to reset the grouping key that you used in the project id grouping.

Filter multidimensional multilevel array to uniq

I have the next probleme, i want to filter a multidimensional and multi level array with for the uniqe one.
An example:
Array
(
[Home] => Array
(
[Kids] => Array
(
[For sleeping] => Array
(
[0] => Sleeping Bags
[1] => mattress
[2] => mattress
[3] => mattress
[4] => Beds
[5] => Beds
[6] => Beds
[..]
The befored array i want to make it with the uniqe values.
I don't know if this is the fastest / shortest answer, but the code below might work for you:
#Function to make a multidimensional array unique
function makeUnique(&$array)
{
foreach($array as $key => &$value)
{
if(is_array($value))
{
makeUnique($value);
$value = array_unique($value);
}
}
return $array;
}
#Example of your array
$exampleArray = Array(
'Home' => Array(
'Kids' => Array(
'For sleeping' => Array(
0 => 'Sleeping Bags',
1 =>'mattress',
2 =>'mattress')
)
)
);
#Make the array unique and print the results
makeUnique($exampleArray);
print_r($exampleArray);
I have resolved this problem. The solution for this problem is:
$test = Array
(
[Home] => Array
(
[Kids] => Array
(
[For sleeping] => Array
(
[0] => Sleeping Bags
[1] => mattress
[2] => mattress
[3] => mattress
[4] => Beds
[5] => Beds
[6] => Beds
[..]
foreach ($test as $key=>$value){
foreach ($value as $key2 => $value2) {
foreach ($value2 as $key3=>$value3) {
$cat[$key][$key2][$key3]= array_unique($value3);
}
}
}

Intersection of two arrays using common key value for comparison

I want to perform an intersection of two arrays that have different structures, but both have one key common (fid). I want a new (filtered second) array after intersection with first array. below is my code and two arrays :
first array:
Array
(
[0] => Array
(
[fid] => 1
)
[1] => Array
(
[fid] => 3
)
)
Second array:
Array
(
[0] => Array
(
[fid] => 9
[functionality] => testing
[funcat_id] => 1
[name] => functionality
)
[1] => Array
(
[fid] => 1
[functionality] => add functionality
[funcat_id] => 1
[name] => functionality
)
[2] => Array
(
[fid] => 2
[functionality] => view functionality category
[funcat_id] => 1
[name] => functionality
)
[3] => Array
(
[fid] => 3
[functionality] => view functionality
[funcat_id] => 1
[name] => functionality
)
[4] => Array
(
[fid] => 4
[functionality] => edit functionality
[funcat_id] => 1
[name] => functionality
)
)
I want this Output :
Array
(
[0] => Array
(
[fid] => 1
[functionality] => add functionality
[funcat_id] => 1
[name] => functionality
)
[1] => Array
(
[fid] => 3
[functionality] => view functionality
[funcat_id] => 1
[name] => functionality
)
)
I tried this code but I'm not getting the right answer:
$result=array_intersect($array1,$array2);
//Or this also
$result=recursive_array_intersect_key($array1,$array2);
Please let me know, if any one can do this ?
I do not know if a function does exists to do this outright, but alternatively, you can just loop them instead:
$result = array();
foreach($array2 as $val2) {
foreach ($array1 as $val1) {
if($val2['fid'] == $val1['fid']) {
$result[] = $val2;
}
}
}
echo '<pre>';
print_r($result);
Sample Output
Or if you're using PHP 5.5 or greater:
$val1 = array_column($array1, 'fid');
$result = array_filter($array2, function($val2) use($val1) {
return in_array($val2['fid'], $val1);
});
foreach($array2 as $val)
{
$i=0;
foreach($array1 as $val1)
{
if($val['fid']==$val1['fid'])
{
$i++;
}
}
if($i!=0)
{
$a[]=$val;
}
}
print_r($a);

How to search for data from one array in another arrays and display it as another fields in CakePHP

I have my array
Array
(
[0] => Dusche
[1] => Mobliert
)
And I have second array which is composed and looks like this:
[0] => Array
(
[id] => 1002
[attribute_id] => 65
[value_id] => 26815
[name] => Garten/-mitbenutzung
[order] => 0
)
[1] => Array
(
[id] => 1003
[attribute_id] => 65
[value_id] => 26811
[name] => Etagenheizung
[order] => 1
)
[2] => Array
(
[id] => 1004
[attribute_id] => 65
[value_id] => 26829
[name] => Balkon/Terrasse
[order] => 2
How can I search this second array with values from the first array and retrieve attribute_id from elements which have the same names?
PHP way:
filteredArray = array();
foreach ($secondArray as $type) {
if (in_array($type['name'], $firstArray)) {
$filteredArray[] = $type['attribute_id'];
}
}
Cake Set way, something along the lines of:
$filteredArray = array();
foreach ($firstArray as $keyword) {
$filteredArray = array_merge($filteredArray, Set::extract("/.[name=$keyword]/attribute_id", $secondArray));
}

Categories