Combining 2 Arrays when value is matched - php

So I have these arrays that is fetched from 2 different database, I would like to combine them in one array when the ['item_name'] and ['name'] is matched then getting the ['id'] from the Array2
I tried doing the in_array but since it's multi dimensional, I can't get the right output I want, I tried foreach also but I can't also get the right output or maybe I'm doing it wrong, I'm running out of idea how I could do the output I wanted.
Example Array1:
Array
(
[0] => Array
(
[item_id] => 1
[item_name] => Bag
[Color] => Purple
)
[1] => Array
(
[item_id] => 2
[item_name] => Pencil
[Color] => Yellow
)
[2] => Array
(
[item_id] => 3
[item_name] => Tumbler
[Color] => Blue
)
[3] => Array
(
[item_id] => 4
[item_name] => Shirt
[Color] => Red
)
)
Example Array2:
Array
(
[0] => Array
(
[id] => 11
[name] => Bag
)
[1] => Array
(
[id] => 22
[name] => Pencil
)
[2] => Array
(
[id] => 33
[name] => Tumbler
)
[3] => Array
(
[id] => 44
[name] => Shirt
)
[4] => Array
(
[id] => 55
[name] => Paper
)
[5] => Array
(
[id] => 66
[name] => Chair
)
[6] => Array
(
[id] => 4
[name] => Notebook
)
)
So my expected output would be:
Array
(
[0] => Array
(
[id] => 11
[name] => Bag
[Color] => Purple
)
[1] => Array
(
[id] => 22
[name] => Pencil
[Color] => Yellow
)
[2] => Array
(
[id] => 33
[name] => Tumbler
[Color] => Blue
)
[3] => Array
(
[id] => 44
[name] => Shirt
[Color] => Red
)
)

You can create a map with the names and the ID from the second array and then loop to modify the first one.
Consider the following code:
$a1 = array("item_id" => 1, "item_name" => "Bag", "Color" => "Purple");
$a2 = array("item_id" => 2, "item_name" => "Pencil", "Color" => "Yellow");
$a3 = array("item_id" => 3, "item_name" => "Tumbler", "Color" => "Blue");
$b1 = array("item_id" => 11, "item_name" => "Bag");
$b2 = array("item_id" => 22, "item_name" => "Pencil");
$b3 = array("item_id" => 33, "item_name" => "Tumbler");
$arr1 = array($a1, $a2, $a3);
$arr2 = array($b1, $b2, $b3);
$map = []; // here keys are names and value are the id
foreach($arr2 as $elem)
$map[$elem["item_name"]] = $elem["item_id"];
$ans = [];
foreach ($arr1 as $elem) {
if (array_key_exists($elem["item_name"], $map)) {
$elem["item_id"] = $map[$elem["item_name"]];
$ans[] = $elem;
}
}
echo print_r($ans);
In this way you achieve complexity of O(n) instead of O(n^2) if trying nested for-loop

Try by using foreach loop.
Check if in foreach loop if any index value match with another array then create a new array with all those values.
You can use counter here to get the value of array inside loop.

Been trying to simplify my code earlier and I think I got it, thanks to anju and David Winder, if anyone interested how I did it, this is how:
index = 0;
foreach ($array1 as $val){
foreach ($array2 as $val2){
if ($val['item_id'] == $val2['id']){
$filtered[$index]['id'] = $val2['id'];
$filtered[$index]['name'] = $val2['name'];
$filtered[$index]['color'] = $val['color'];
$index++;
}
}
}

Related

Taking values from one multidimensional array and putting it in the other multidimensional array based on matching value from first key

I have two arrays, $full_list and $only_titles with matching value based on first key.
$full_list:
Array
(
[0] => Array
(
[0] => samsung-a40
[1] => Samsung A40 Phone
[2] =>
[3] => 21
[4] => 334234
[5] => 0
)
[1] => Array
(
[0] => samsung-a72
[1] => Galaxy A72 Phone
[2] =>
[3] => 230
[4] => 239049
[5] => 0
)
[2] => Array
(
[0] => lg-k61
[1] => LG K61 Phone
[2] =>
[3] => 22
[4] => 249582
[5] => 0
)
etc...
$only_titles:
Array
(
[0] => Array
(
[0] => samsung-a40
[1] => Black Phone Case For Samsung A40
)
[1] => Array
(
[0] => lg-k61
[1] => Red Case LG K61 Phone
)
[2] => Array
(
[0] => samsung-a72
[1] => Folding Phone Case for Galaxy A72 Phone
)
etc...
I want to take value from second key from $only_title array (its basicaly long product title) and replace it in the $full_list array:
$final_result:
Array
(
[0] => Array
(
[0] => samsung-a40
[1] => Black Phone Case For Samsung A40 // title from $only_titles
[2] =>
[3] => 21
[4] => 334234
[5] => 0
)
[1] => Array
(
[0] => samsung-a72
[1] => Folding Phone Case for Galaxy A72 Phone // title from $only_titles
[2] =>
[3] => 230
[4] => 239049
[5] => 0
)
[2] => Array
(
[0] => lg-k61
[1] => Red Case LG K61 Phone // title from $only_titles
[2] =>
[3] => 22
[4] => 249582
[5] => 0
)
etc...
I have tried array_replace_recursive(), but the problem with this is that it expects that the order of subarrays are the same. But as you can see in both arrays the second subarrays dont match. With array_replace_recursive() i get the second subarray wrong:
[1] => Array
(
[0] => samsung-a72
[1] => Red Case LG K61 Phone // this is wrong
[2] =>
[3] => 230
[4] => 239049
[5] => 0
)
How can I check if values from first key match?
You can utilize array_map and array_search for your task.
$items = array_map(function($item) use ($only_titles) {
$index = array_search($item[0], array_column($only_titles, 0));
if($index === false) return;
$item[1] = $only_titles[$index][1];
return $item;
}, $full_list);
array_map() takes $full_list and iterate each item as $item,
then for each item, we look for the matching title with array_search()
It will return an index from $only_titles.
We can use $index to reference and assign the long title to item.
The result are in $items
This script will help you to solve your problem
<?php
$full_array = [
[
'samsung-a40',
'Samsung A40 Phone',
null,
21,
334234,
0,
],
[
'samsung-a72',
'Galaxy A72 Phone',
null,
230,
239049,
0,
],
];
$only_titles = [
[
'samsung-a40',
'Black Phone Case For Samsung A40',
],
[
'samsung-a72',
'Red Case LG K61 Phone ',
],
];
$formattedOnlyTitles = [];
foreach ($only_titles as $value) {
$formattedOnlyTitles[$value[0]] = $value[1];
}
$fullArrayWithNewTitle = [];
foreach ($full_array as $value) {
if (isset($formattedOnlyTitles[$value[0]])) {
$value[1] = $formattedOnlyTitles[$value[0]];
}
$fullArrayWithNewTitle[] = $value;
}
print_r($fullArrayWithNewTitle);
output
Array
(
[0] => Array
(
[0] => samsung-a40
[1] => Samsung A40 Phone
[2] =>
[3] => 21
[4] => 334234
[5] => 0
)
[1] => Array
(
[0] => samsung-a72
[1] => Galaxy A72 Phone
[2] =>
[3] => 230
[4] => 239049
[5] => 0
)
)
First I change the format of the title_only var to make is easy to work with it in the next foreach
$formattedOnlyTitles = [];
foreach ($only_titles as $value) {
$formattedOnlyTitles[$value[0]] = $value[1];
}
In the next foreach I just check the title with my new formatted title_only array
if (isset($formattedOnlyTitles[$value[0]])) {
$value[1] = $formattedOnlyTitles[$value[0]];
}
And then change the title if I need

Append one array values as key value pair to another array php

I have two arrays both guaranteed to be the same length. The two arrays are of the following structures
array1
Array
(
[0] => Array
(
[id] => 841052
[store] => 11
[position] => 1
)
[1] => Array
(
[id] => 1613197
[store] => 11
[position] => 401
)
[2] => Array
(
[id] => 1648966
[store] => 11
[position] => 1
)
[3] => Array
(
[id] => 1656857
[store] => 11
[position] => 1
)
....
....
)
array2
Array
(
[0] => 5/20/2019
[1] => 7/7/2019
[2] => 12/16/2018
...
...
)
How do I append every value of array2 as a key value pair to array1 to get the following array. The key name can be whatever I just chose date.
Array
(
[0] => Array
(
[id] => 841052
[store] => 11
[position] => 1
[date] => 5/20/2019
)
[1] => Array
(
[id] => 1613197
[store] => 11
[position] => 401
[date] => 7/7/2019
)
[2] => Array
(
[id] => 1648966
[store] => 11
[position] => 1
[date] => 12/16/2018
)
)
...
...
...
I have tried
array_push($array1, $array2);
It just pushed it to the last element of the array. I thought of using two foreach loops but couldn't get ti to work. Is there a built in php function that will do this, or do I have to do it in loops.
Just walk $array1 and modify each sub-array by adding the new key and the value of $array2 with the same key:
array_walk($array1, function(&$v, $k) use($array2) { $v['date'] = $array2[$k]; });
try this:
$array1 = array(array("id" => 841052, "store" => "11", "position" => "1"), array("id" => 1613197, "store" => "11", "position" => "401"),);
$array2 = array("5/20/2019", "7/7/2019");
foreach ($array1 as $index => $valuearray1) {
if (array_key_exists($index, $array2)) {
$array1[$index]["date"] = $array2[$index];
}
}
var_dump($array1);

Merging two array elements into one array element in PHP

I want to merge two arrays into one array as follows,
Array1:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
)
)
Array2:
Array
(
[0] => Array
(
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
Expected array result is:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
How to merge these array elements into one array element ?
foreach ($origArray as $key => &$subArray)
$subArray += $arrayToBeAdded[$key];
Where $origArray is your array which is to be merged into and $arrayToBeAdded the array you merge into.
User array_merge_recursive():
$final = array_merge_recursive($array1, $array2);
Try this little known overload of the + operator for arrays:
$result = $array1[0] + $array2[0]
Use function array_merge($array1[0], $array2[0]) . Following is the example for the same
$array1 = array(0=>array('1'=>1,'2'=>2,'3'=>3));
$array2 = array(0=>array('4'=>4,'5'=>5,'6'=>6));
$result[0] = array_merge($array1[0],$array2[0]);
echo '<pre>';
print_r($result);
Since you have unique keys, you could use something as simple as the + operator (union)...
For example:
$arr1 = [1=>'testing',2=>'stack',3=>'overflow'];
$arr2 = [4=>'something',5=>'else',6=>'here'];
$arr3 = $arr1 + $arr2;
print_r($arr3);
Results:
Array ( [1] => testing [2] => stack [3] => overflow [4] => something [5] => else [6] => here )
For this php has multiple functions. You can use $arrays = array_combine($array1, $array2);.
PHP.net - array_combine
Hope it helped!

I've spent hours trying to get these array keys into variables but everything I try is not working

I have an array of all possible combinations of values, a bit like working out what monetary values I could make with only certain coins. Now I have an array built but much of the useful data are keys and not values.
A small snippet is below:
Each root key is an array with keys total, denomination and quantity. Each of the quantities multiplied by the denominations total the total. While I've been able to access the total easily enough I just can't get a handle on the denominations and the quantities.
It's my plan to output to separate radio buttons like so:
foreach($array as $arr)
{
echo '<input type="radio" name="name" value="'.$arr[$total].'">';
foreach($arr[denom] as $index => $d)
{
echo $d[qty][$index].' x '.$d[denom][$index].' = '.($qty[$index]*$denom[$index]).'<br>';
}
}
Here's the array I have, any help would be much appreciate, I'm usually great at this bot it's driving me crazy
Array
(
[2] => Array
(
[total] => 105
[denom] => Array
(
[0] => 105
)
[qty] => Array
(
[0] => 1
)
)
[3] => Array
(
[total] => 210
[denom] => Array
(
[0] => 105
)
[qty] => Array
(
[0] => 2
)
)
[4] => Array
(
[total] => 300
[denom] => Array
(
[0] => 300
)
[qty] => Array
(
[0] => 1
)
)
[5] => Array
(
[total] => 405
[denom] => Array
(
[0] => 300
[1] => 105
)
[qty] => Array
(
[0] => 1
[1] => 1
)
)
[6] => Array
(
[total] => 500
[denom] => Array
(
[0] => 500
)
[qty] => Array
(
[0] => 1
)
)
[7] => Array
(
[total] => 605
[denom] => Array
(
[0] => 500
[1] => 105
)
[qty] => Array
(
[0] => 1
[1] => 1
)
)
Constant non-numeric array indices should be written like any other string, i.e. encapsulated in quotes.
foreach($array as $arr) {
echo '<input type="radio" name="name" value="'.$arr['total'].'">';
foreach($arr['denom'] as $index => $d){
for ($j = 0;$j < count($denom);$j++) {
echo $d['qty'][$j].' x '.$d['denom'][$j].' = ';
echo ($d['qty'][$j]*$d['denom'][$j]) . '<br>';
}
}
}
First format your array like this in my code, add 6, 7 array elements. I modify for loop too.
<?php
$array = array(2 => array('total' => 105, 'denom' => array(0 => 105), 'qty' => array(0 => 1)),
3 => array('total' => 210, 'denom' => array(0 => 105), 'qty' => array(0 => 2)),
4 => array('total' => 300, 'denom' => array(0 => 300), 'qty' => array(0 => 1)),
5 => array('total' => 405, 'denom' => array(0 => 300, 1 => 105), 'qty' => array(0 => 1, 1 => 1)),
);
foreach($array as $arr)
{
//var_dump($arr);
echo '<input type="radio" name="name" value="'.$arr['total'].'">';
foreach($arr['denom'] as $index => $d)
{
echo $arr['qty'][$index].' x '.$d.' = '.($arr['qty'][$index]*$d).'<br>';
}
}
?>

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