2 arrays match data into 1 array with PHP - php

I have 2 array's, first array have for example ItemID of my item, second array have description about my item. I want to match data into 1 array.
It looks like:
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
Items in arrays don't have the same value like ID, but they are in the same order so:
Description for the first item in rgInventory is in the first array inside rgDescriptions.
What should I do to match for example id from rgInventory with name from rgDescriptions in the same array for example $backpack = array();?
Regards for you.

Try this:
<?php
$array1 = array('rgInventory' =>
array(
'1234567890' => array(
'id' => 1234567890,
'classid' => 123456789,
'instanceid' => 987654321,
'amount' => 1,
'pos' => 1
)
)
);
$array2 = array(
'rgDescriptions' => array(
'192837465_918273645' => array(
'appid' => 730, 'name' => 'Something')
)
);
Create new function to combine the two arrays into one array:
function array_sum_recursive($data1, $data2) {
if (!is_array($data1) && !is_array($data2)) {
return $data1 + $data2;
}
// deepest array gets precedence
if (!is_array($data2)) {
return $data1;
}
if (!is_array($data1)) {
return $data2;
}
//merge and remove duplicates
$keys = array_unique(array_merge(array_keys($data1), array_keys($data2)));
foreach ($keys as $key) {
if (isset($data1[$key]) && isset($data2[$key])) {
$result[$key] = array_sum_recursive($data1[$key], $data2[$key]);
} else if (isset($data1[$key])) {
$result[$key] = $data1[$key];
} else {
$result[$key] = $data2[$key];
}
}
if(empty($result)){
echo "no result";
die();
}else{
return $result;
}
}
Put the two array in one array $newarray:
$newonearray = array_sum_recursive($array1, $array2);
echo '<pre>';
print_r($newonearray);
?>
And you will get this:
Array
(
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
)
Hope this may help.

You can use function each to get each element of both arrays, then merge its with array_merge and save this new item to backup array.
Try something like this
<?php
$rgInventory = ['firstInv' => ['invId' => 1], 'secondInv' => ['invId' => 2]];
$rgDescriptions = ['firstDesc' => ['descId' => 1], 'secondDesc' => ['descId' => 2]];
if (count($rgInventory) && count($rgInventory) == count($rgDescriptions)) {
$backpack = [];
while($inventory = each($rgInventory)) {
$description = each($rgDescriptions);
$item = array_merge($inventory['value'], $description['value']);
$backpack[] = $item;
}
var_dump($backpack);
}
Output will be:
array(2) {
[0]=>
array(2) {
["invId"]=>
int(1)
["descId"]=>
int(1)
}
[1]=>
array(2) {
["invId"]=>
int(2)
["descId"]=>
int(2)
}
}

Related

How to merge two arrays diferents on one

How to update an array of objects, adding the quantities if you already have the same ID, or if you have not created a new object.
I tried to explain in the code with the arrays and also with the idea of how I would like the result to be.
old Array
$a1 = [
array(
"id" => 1,
"qty" => 1
),
array(
"id" => 2,
"qty" => 1
)
];
$a2 = [
array(
"id" => 1,
"qty" => 1
)
];
$output = array_merge($a1, $a2);
echo '<pre>';
print_r($output);
echo '</pre>';
Result Error:
Array
(
[0] => Array
(
[id] => 1
[qty] => 1
)
[1] => Array
(
[id] => 2
[qty] => 1
)
[2] => Array
(
[id] => 1
[qty] => 1
)
)
What I need, in addition to if the ID does not contain, add.
Array
(
[0] => Array
(
[id] => 1
[qty] => 2
)
[1] => Array
(
[id] => 2
[qty] => 1
)
)
You can take the first array as base, then search for the key (if existing) where the product matches the id. Then either add the quantity and recalculate the price or you just add the reformatted element (id to product conversion).
$result = $a;
foreach($b as $element) {
$matchingProductIndex = array_search($element['id'], array_column($a, 'product'));
if ($matchingProductIndex !== false) {
$pricePerUnit = $result[$matchingProductIndex]['price'] / $result[$matchingProductIndex]['qty'];
$result[$matchingProductIndex]['qty'] += $element['qty'];
$result[$matchingProductIndex]['price'] = $result[$matchingProductIndex]['qty'] * $pricePerUnit;
} else {
$result[] = [
'qty' => $element['qty'],
'product' => $element['id'],
'price' => $element['price'],
];
}
}
print_r($result);
Working example.
Loop through both arrays with foreach and check the ids against each other.
https://paiza.io/projects/lnnl5HeJSFIOz_6KD6HRIw
<?php
$arr1 = [['qty' => 4, 'id' => 4],['qty' => 1,'id' => 30]];
$arr2 = [['id' => 30, 'qty' => 19],['id' => 31, 'qty' => 2]];
$arr3 = [];
foreach($arr1 as $iArr1){
$match = false;
foreach($arr2 as $iArr2){
if($iArr1['id'] === $iArr2['id']){
$arr3[] = ['id' => $iArr1['id'], 'qty' => $iArr1['qty'] + $iArr2['qty']];
$match = true;
}
}
if(!$match){
$arr3[] = $iArr1;
$arr3[] = $iArr2;
}
}
print_r($arr3);
?>
One approach could be one I more often suggested.
First lets merge $a2 with one to simplify looping over one larger collection.
If we then create a small mapping from id to its index in the result array we can update the running total of qty.
$map = [];
$result = [];
// Merge the two and do as per usual, create a mapping
// from id to index and update the qty at the corresponding index.
foreach (array_merge($a1, $a2) as $subarr) {
$id = $subarr['id'];
if (!key_exists($id, $map)) {
$index = array_push($result, $subarr) - 1;
$map[$id] = $index;
continue;
}
$result[$map[$id]]['qty'] += $subarr['qty'];
}
echo '<pre>', print_r($result, true), '</pre>';
Output:
Array
(
[0] => Array
(
[id] => 1
[qty] => 2
)
[1] => Array
(
[id] => 2
[qty] => 1
)
)

How to merge an array with child elements

I have an array with same customerid. I want to merge all same customerid arrays in to one with few amends to the array.
Array
(
[0] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[profession_id] => 8
[profession_name] => Producer
)
[1] => Array
(
[customerid] => 1
[customer_fullname] => John
[profession_id] => 8
[profession_name] => Producer
)
[2] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[profession_id] => 7
[profession_name] => Camera
)
)
So now I want a new array to be created like this:
Array(
[customerid] => 13
[customer_fullname] => Chris
[new_array] => array(
[0]=>[profession_id] => 8, [profession_name] => Producer,
[1]=>[profession_id] => 7, [profession_name] => Camera
)
)
Spent some time on it but wasn't able to get it right
There are better approaches if you're merging lots of records, but if you want a way to just merge two records as stated, I'd just do this:
$array1 = array(
'customerid' => 13
'customer_fullname' => 'John',
'profession_id' => 8,
'profession_name' => 'Producer'
);
$array2 = array(
'customerid' => 13
'customer_fullname' => 'John',
'profession_id' => 7,
'profession_name' => 'Director'
);
function merge_customers($customerA, $customerB)
{
$newCustomer = array();
if ($customerA['customerid'] == $customerB['customerid'])
{
$newCustomer['customerid'] = $customerA['customerid'];
$newCustomer['customer_fullname'] = $customerA['customer_fullname'];
$newCustomer['new_array'] = array(
array(
'profession_id' => $customerA['profession_id'],
'profession_name' => $customerA['profession_name']
),
array(
'profession_id' => $customerB['profession_id'],
'profession_name' => $customerB['profession_name']
)
);
return $newCustomer;
}
/* We can't merge these if they're different customers. */
return NULL;
}
The extended solution which is also well-suited for finding and "merging" multiple groups of entries which has same customerid. Used functions: array_filter, array_count_values, array_keys, array_walk, array_chunk and array_values:
// supposing $arr is your initial array
// finds which 'customerid' has multiple entries
$dupIds = array_filter(array_count_values(array_column($arr, "customerid")), function($v) {
return $v > 1;
});
$dupIds = array_keys($dupIds);
$result = [];
array_walk($arr, function($v) use(&$result, $dupIds) {
if (in_array($v['customerid'], $dupIds)) {
$parts = array_chunk($v, 2, true);
if (!isset($result[$v['customerid']])) {
$result[$v['customerid']] = $parts[0] + ['new_array' => [$parts[1]]];
} else {
$result[$v['customerid']]['new_array'][] = $parts[1];
}
}
});
print_r(array_values($result));
The output:
Array
(
[0] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[new_array] => Array
(
[0] => Array
(
[profession_id] => 8
[profession_name] => Producer
)
[1] => Array
(
[profession_id] => 7
[profession_name] => Camera
)
)
)
)
Quick hack, maybe there is a nicer solution.
Note: The second "for each" loop is only needed if there is the possibility that the arrays don't have the same fields.
function merge($array1, $array2){
$result = array();
foreach($array1 as $key => $value){
if(isset($array2[$key]) && $array2[$key]!=$array1[$key]){
$result[$key][]=$value;
$result[$key][]=$array2[$key];
}else{
$result[$key]=$value;
}
}
foreach($array2 as $key => $value){
if(!isset($result[$key])){
$result[$key] = $value;
}
}
return $result;
}
print_r(merge($array1, $array2));

Php string comparision in multidimensional array

I have two multidimensional array
Array
(
[0] => Array
(
[code] => 2079
[label] => Nike
)
[1] => Array
(
[code] => 1080
[label] => Adidas
)
)
Array
(
[0] => Array
(
[manufacturers_id] => 2753
[manufacturers_name] => Reebok
)
[1] => Array
(
[manufacturers_id] => 2526
[manufacturers_name] => Adidas
)
[2] => Array
(
[manufacturers_id] => 34
[manufacturers_name] => Nike
)
)
I want to do string matching of a key label of array 1 with key manufacturer_name of array 2. What is the best approach in multidimensional arrays ?
You could loop trough the arrays.
foreach ($multi_array1 as $value) {
foreach ($multi_array2 as $value2) {
If ($value[label] === $value2 [manufacturer_name])
{}
}
}
If you want to match by label and manufacturers_name, then I suggest you reindex your arrays by those fields:
$by_label = [];
foreach($first_array as $element) {
$by_label[$element['label']] = $element['code'];
}
$by_name = [];
foreach($second_array as $element) {
$by_label[$element['manufacturers_name']] = $element['manufacturers_id'];
}
foreach($by_label as $label => $code) {
print "Label is $label, code is $code, id is {$by_name[$label]}";
}
foreach($by_name as $name => $id) {
print "Name is $name, id is $id, label is {$by_label[$name]}";
}
Just use foreach to accomplish your desire result.
Array
$firstArr = array(
array("code" => 2079, "label" => 'Nike'),
array("code" => 1080, "label" => 'Adidas')
);
$secArr = array(
array("manufacturers_id" => 2753, "manufacturers_name" => 'Reebok'),
array("manufacturers_id" => 2526, "manufacturers_name" => 'Adidas'),
array("manufacturers_id" => 34, "manufacturers_name" => 'Nike')
);
Foreach Technique:
foreach($firstArr as $value){
if(in_array_sec($value['label'])){
echo $value['label'].' found in second array.';
}else{
echo $value['label'].' not found in second array.';
}
}
function in_array_sec($val_one){
global $secArr;
$flag = false;
foreach($secArr as $value){
if($value['manufacturers_name'] == $val_one){
$flag = true;
break;
}
else
$flag = false;
}
return $flag;
}
Result:
Nike found in second array.
Adidas found in second array.

Select and delete random keys from multidimensional array

I have one problem with randomness.
I have example array.
$example=array(
'F1' => array('test','test1','test2','test5'),
'F2' => array('test3', 'test4'),
'F3' => array('one','twoo','threee','x'),
'F5' => array('wow')
)
I want to choose random keys from array to other array with specified size. In this second array I want values from other groups.
For example i got
$amounts = array(4,3,1,2,1);
I want to choose randomly specified ammount of variables ($amount) from $example, but of course - always from other groups.
Example result:
$result=(
array(4) => ('test','test4','x','wow'),
array(3) => ('test2','test3','three'),
array(1) => ('test1')
array(2) => ('test5','one')
array(1) => ('twoo')
What I tried so far?
foreach($amounts as $key=>$amount){
$random_key[$key]=array_rand($example,$amount);
foreach($result[$key] as $key2=>$end){
$todelete=array_rand($example[$end]);
$result[$key][$key2]=$example[$amount][$todelete]
}
}
I don't know now, what to fix or to do next.
Thanks for help!
$example = array(
'F1' => array('test', 'test1', 'test2', 'test5'),
'F2' => array('test3', 'test4'),
'F3' => array('one', 'twoo', 'threee', 'x'),
'F5' => array('wow')
);
$amounts = array(4, 3, 1, 2, 1);
$result = array();
$example = array_values($example);
//randomize the array
shuffle($example);
foreach ($example as $group) {
shuffle($group);
}
//sort the example array by child length
usort($example, function ($a, $b) {
return count($b) - count($a);
});
foreach ($amounts as $amount) {
$tmpResult = array();
for ($i = 0; $i < $amount; $i++) {
if(empty($example[$i])){
throw new \InvalidArgumentException('The total number of values in the array exceed the amount inputed');
}
$tmpResult[] = array_pop($example[$i]);
}
$result[] = $tmpResult;
//sort the example array again by child length
usort($example, function ($a, $b) {
return count($b) - count($a);
});
}
print_r($result);
test result:
Array
(
[0] => Array
(
[0] => test5
[1] => x
[2] => test4
[3] => wow
)
[1] => Array
(
[0] => test2
[1] => threee
[2] => test3
)
[2] => Array
(
[0] => test1
)
[3] => Array
(
[0] => twoo
[1] => test
)
[4] => Array
(
[0] => one
)
)

how to get value from associative array

This is my array :
Array
(
[0] => Array
(
[0] => S No.
[1] => Contact Message
[2] => Name
[3] => Contact Number
[4] => Email ID
)
[1] => Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
[2] => Array
(
[0] => 2
[1] => This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.
[2] => shiva <br/>(Individual)
[3] => 2135467890
[4] => sauron82#yahoo.co.in
)
)
How can I retrieve all data element wise?
You can get information about arrays in PHP on the official PHP doc page
You can access arrays using square braces surrounding the key you like to select [key].
So $array[1] will give yoo:
Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
And $array[1][2] will give you:
lopa <br/>(Individual)
Or you can walkt through the elements of an array using loops like the foreach or the for loop.
// perfect for assoc arrays
foreach($array as $key => $element) {
var_dump($key, $element);
}
// alternative for arrays with seamless numeric keys
$elementsCount = count($array);
for($i = 0; $i < $elementsCount; ++$i) {
var_dump($array[$i]);
}
You have integer indexed elements in multidimensional array. To access single element from array, use array name and it's index $myArray[1]. To get inner element of that previous selected array, use second set of [index] - $myArray[1][5] and so on.
To dynamically get all elements from array, use nested foreach loop:
foreach ($myArray as $key => $values) {
foreach ($values as $innerKey => $value) {
echo $value;
// OR
echo $myArray[$key][$innerKey];
}
}
The solution is to use array_reduce:
$header = array_map(
function() { return []; },
array_flip( array_shift( $array ) )
); // headers
array_reduce( $array , function ($carry, $item) {
$i = 0;
foreach( $carry as $k => $v ) {
$carry[$k][] = $item[$i++];
}
return $carry;
}, $header );
First of all we get the header from the very first element of input array. Then we map-reduce the input.
That gives:
$array = [['A', 'B', 'C'], ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']];
/*
array(3) {
'A' =>
array(3) {
[0] =>
string(2) "a1"
[1] =>
string(2) "a2"
[2] =>
string(2) "a3"
}
'B' =>
array(3) {
[0] =>
string(2) "b1"
[1] =>
string(2) "b2"
[2] =>
string(2) "b3"
}
'C' =>
array(3) {
[0] =>
string(2) "c1"
[1] =>
string(2) "c2"
[2] =>
string(2) "c3"
}
}
*/
I think this is what you are looking for
$array = Array
(
0=> Array
(
0 => 'S No.',
1 => 'Contact Message',
2 => 'Name',
3 => 'Contact Number',
4 => 'Email ID'
),
1 => Array
(
0 => 1,
1 => 'I am interested in your property. Please get in touch with me.',
2 => 'lopa <br/>(Individual)',
3 => '1234567890',
4 => 'loperea.ray#Gmail.com',
),
2 => Array
(
0 => 2,
1 => 'This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.',
2 => 'shiva <br/>(Individual)',
3 => '2135467890',
4 => 'sauron82#yahoo.co.in',
)
);
$result_array = array();
array_shift($array);
reset($array);
foreach($array as $x=>$array2){
foreach($array2 as $i => $arr){
if($i == 1){
$result_array[$x]['Contact Message'] = $arr;
}elseif($i == 2){
$result_array[$x]['Name'] = $arr;
}elseif($i == 3){
$result_array[$x]['Contact Number'] =$arr;
}elseif($i == 4){
$result_array[$x]['Email ID'] = $arr;
}
}
}
print_r($result_array);

Categories