Matching one array value to another and retrieving/replacing matched - php

I'm trying to retrieve the "location" in $arrayB by using the key "locationid" in $arrayA:
$arrayA=Array
(
(0) => Array
(
(domain) => 'testing.com',
(locationid) => '7',
(description) => 'Lorem'
),
(1) => Array
(
(domain) => 'testing2.com',
(locationid) => '6',
(description) => 'Ipsum'
),
(2) => Array
(
(domain) => 'testing3.com',
(locationid) => '1',
(description) => 'Foo'
)
);
$arrayB=Array
(
(0) => Array
(
(locationid) => '1',
(location) => 'London'
),
(1) => Array
(
(locationid) => '6',
(location) => 'New York'
),
(2) => Array
(
(locationid) => '7',
(location) => 'Tokyo'
)
);
And then ultimately ending up with $arrayC which would be something along the lines of:
$arrayC=Array
(
(0) => Array
(
(domain) => 'testing.com',
(location) => 'Tokyo',
(description) => 'Lorem'
),
etc...
);
What would be the best way to go about this? I guess some sort of "foreach" function but I can't get my head around it!
Many thanks

One nested loop would do-it but I think this is more readable
<?php
$arrayA=Array
(
'0' => Array
(
'domain' => 'testing.com',
'locationid' => '7',
'description' => 'Lorem'
),
'1' => Array
(
'domain' => 'testing2.com',
'locationid' => '6',
'description' => 'Ipsum'
),
'2' => Array
(
'domain' => 'testing3.com',
'locationid' => '1',
'description' => 'Foo'
)
);
$arrayB=Array
(
'0' => Array
(
'locationid' => '1',
'location' => 'London'
),
'1' => Array
(
'locationid' => '6',
'location' => 'New York'
)
);
function getDomain($id, $list) {
foreach ($list as $domain) {
if ($domain['locationid'] == $id) {
return $domain;
}
}
}
$arrayC = array();
foreach ($arrayB as $id) {
$newData = getDomain($id['locationid'], $arrayA);
$newData['location'] = $id['location'];
$arrayC[] = $newData;
}
var_dump($arrayC);

$arrayB = array( 7 => 'Tokyo' );
$arrayC = array_map( function(&$a) use ($arrayB) {
$a['location'] = $arrayB[$a['locationid']];
unset([$a['locationid']);
return $a;
}, $arrayA);
maybe like that.

$arrayA = array(
array('domain' => 'testing.com', 'locationid' => '7', 'description' => 'Lorem'),
array('domain' => 'testing2.com', 'locationid' => '6', 'description' => 'Ipsum'),
array('domain' => 'testing3.com', 'locationid' => '1', 'description' => 'Foo')
);
$arrayB = array(
array('locationid' => '1', 'location' => 'London'),
array('locationid' => '6', 'location' => 'New York'),
array('locationid' => '7', 'location' => 'Tokyo')
);
$arrayA_a = array();
foreach($arrayA AS $arrayA_b)
{
$arrayA_a["$arrayA_b[locationid]"] = $arrayA_b;
}
$arrayB_a = array();
foreach($arrayB AS $arrayB_b)
{
$arrayB_a["$arrayB_b[locationid]"] = $arrayB_b;
}
$arrayC = array();
foreach($arrayA_a AS $arrayA_a_key => $arrayA_a_value)
{
$arrayC["$arrayA_a_key"]['domain'] = $arrayA_a_value['domain'];
$arrayC["$arrayA_a_key"]['description'] = $arrayA_a_value['description'];
$arrayC["$arrayA_a_key"]['location'] = $arrayB_a["$arrayA_a_key"]['location'];
}
print_r($arrayC);
Array
(
[7] => Array
(
[domain] => testing.com
[description] => Lorem
[location] => Tokyo
)
[6] => Array
(
[domain] => testing2.com
[description] => Ipsum
[location] => New York
)
[1] => Array
(
[domain] => testing3.com
[description] => Foo
[location] => London
)
)
If you want to reset the keys of $arrayC:
$arrayC = array_merge($arrayC);
Array
(
[0] => Array
(
[domain] => testing.com
[description] => Lorem
[location] => Tokyo
)
[1] => Array
(
[domain] => testing2.com
[description] => Ipsum
[location] => New York
)
[2] => Array
(
[domain] => testing3.com
[description] => Foo
[location] => London
)
)

Related

How to merge two array if one item exist in both array?

I want to expand my city array with post code value.
If the city_postcode array contain city array name record then push postcode value into city array. That's what i want to achive somehow.
city array:
Array
(
[0] => Array
(
[id] => 1
[city] => Budapest
[population] => 1700000
)
[1] => Array
(
[id] => 2
[city] => Szeged
[population] => 160000
)
)
city_postcode array:
Array
(
[0] => Array
(
[name] => Budapest
[post_code] => 12345
)
[1] => Array
(
[name] => Szeged
[post_code] => 33356
)
)
The result I want:
Array
(
[0] => Array
(
[id] => 1
[city] => Budapest
[population] => 1700000
[post_code] => 12345
)
[1] => Array
(
[id] => 2
[city] => Szeged
[population] => 160000
[post_code] => 33356
)
)
If you can rely on the cities and post codes to be equal in length and sorted, you could just do something like this:
<?php
$cities = array(
array("id"=>1,"city"=>"Budapest","Population"=>"1700000"),
array("id"=>2,"city"=>"Szeged","Population"=>"160000")
);
$cityPostCode = array(
array("name"=>"Budapest","post_code"=>12345),
array("name"=>"Szeged","post_code"=>33356)
);
for($i = 0; $i < count($cities); $i++){
$cities[$i]['post_code'] = $cityPostCode[$i]['post_code'];
}
print_r($cities);
Other wise you could do something more dyanmic like:
function _parsePostCode($targetName,$targetArr){
foreach($targetArr as $el){
if($el['name'] == $targetName){
return $el['post_code'];
}
}
return false;
}
for($i = 0; $i < count($cities); $i++){
$cities[$i]['post_code'] = _parsePostCode($cities[$i]['city'],$cityPostCode);
}
print_r($cities);
As an alternative you can use 'reference' PHP in foreach loop as follows
$city = array(
0 => array(
'id' => 1,
'city' => "Budapest",
'population' => 1700000
),
1 => array(
'id' => 2,
'city' => "Szeged",
'population' => 160000
)
);
$city_postcode = array(
0 =>array(
'name' => 'Budapest',
'post_code' => 12345
),
1 => array(
'name' => 'Szeged',
'post_code' => 33356
)
);
foreach ($city as $ckey => &$cval) {
$cval['post_code'] = $city_postcode[$ckey]['post_code'];
}
unset($cval);
var_dump($city);
You can use this simple approach :
<?php
$city = array(
0 => array(
'id' => 1,
'city' => "Budapest",
'population' => 1700000
),
1 => array(
'id' => 2,
'city' => "Szeged",
'population' => 160000
)
);
$city_postcode = array(
0 => array(
'name' => 'Budapest',
'post_code' => 12345
),
1 => array(
'name' => 'Szeged',
'post_code' => 33356
)
);
function apply_post_code(&$item, $key, $postcode)
{
$item['post_code'] = $postcode[ $key ][ 'post_code' ];
}
array_walk($city, 'apply_post_code', $city_postcode);
var_dump($city);
Note that the $city variable has been passes by reference

PHP : How to make parallel arrays from multidimentional array

I have this type of array
$arr = array(
0 => array(
0 => array(
'name' => 'test1',
'country' => 'abc'
)
1 => array(
'name' => 'test2',
'country' => 'xyz'
)
)
1 => array(
'name' => 'test3',
'country' => 'pqr'
)
);
How can I make all arrays as parallel arrays. So that all sub arrays are parallel to each other without using any loop.
Like this
$arr = array(
0 => array(
'name' => 'test1',
'country' => 'abc'
)
1 => array(
'name' => 'test2',
'country' => 'xyz'
)
2 => array(
'name' => 'test3',
'country' => 'pqr'
)
);
Any help is much appreciated. !
A dynamic version of Nigel's code would be to loop the array and merge each subarray.
$new = [];
foreach($arr as $subarr){
$new = array_merge($new, $subarr);
}
var_dump($new);
https://3v4l.org/np2ZD
You could simply merge the arrays...
$out = array_merge($arr[0], [$arr[1]]);
print_r($out);
Which gives...
Array
(
[0] => Array
(
[name] => test1
[country] => abc
)
[1] => Array
(
[name] => test2
[country] => xyz
)
[2] => Array
(
[name] => test3
[country] => pqr
)
)

Merge and group rows from multiple 2d arrays based on a shared column value then push another column's data into subarrays

Scenario:
I have these 2 arrays:
array1:
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => 50
)
[2] => Array
(
[label] => dispatched
[fillColor] => #6ecf70
[data] => 10
)
[3] => Array
(
[label] => delivered
[fillColor] => #f89406
[data] => 1
)
[4] => Array
(
[label] => invoiced
[fillColor] => #3a87ad
[data] => 2
)
)
array2:
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => Array
(
[0] => 1
)
)
)
The result I need is
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => Array
(
[0] => 50
[1] => 1
)
)
[2] => Array
(
[label] => dispatched
[fillColor] => #6ecf70
[data] => Array
(
[0] => 10
[1] => 0
)
)
[3] => Array
(
[label] => delivered
[fillColor] => #f89406
[data] => Array
(
[0] => 1
[1] => 0
)
)
[4] => Array
(
[label] => invoiced
[fillColor] => #3a87ad
[data] => Array
(
[0] => 2
[1] => 0
)
)
)
There are only 4 labels:
pending
dispatched
delivered
invoiced
Please note that the arrays are just an example. It can happen that the first array has no values at all or just 2 and the second array have 3 values or none.
Because of that constraint above I'm thinking to use array_replace and having an array called
base_array = ["pending", "dispatched", "delivered", "invoiced"]
I have tried to loop the base_array and try to match the array1 with array2 if label exist.
Basically, if key (which is label) is not exist in any of array1 or array2 then the value replaced will be 0 in the resulting array.
I have tried
foreach($base_array as $key => $value) {
if(in_array($key, $array1[$key])) {
$array[$key] = $array1[$key];
}
}
but it looks like I'm lost on these multi dimensional arrays and replacing. Any help will be really appreciated. Thanks.
From what i understand from your question you can do it like this :-
$array = array(
'1' => Array
(
'label' => 'pending',
'fillColor' => '#468847',
'data' => '50'
),
'2' => Array
(
'label' => 'dispatched',
'fillColor' => '#6ecf70',
'data' => '10'
),
'3 ' => Array
(
'label' => 'delivered',
'fillColor' => '#f89406',
'data' => '1'
),
'4' => Array
(
'label' => 'invoiced',
'fillColor' => '#3a87ad',
'data' => '2'
),
);
$array2 = array
(
'1' => Array
(
'label' => 'pending',
'fillColor' => '#468847',
'data' => array
(
'0' => '1'
)
)
);
$temp = array();
$i = 0;
foreach ($array as $key => $value) {
$temp[$key]['label'] = $value['label'];
$temp[$key]['fillColor'] = $value['fillColor'];
foreach ($array2 as $key2 => $value2) {
if ($value['fillColor'] == $value2['fillColor'] && $value['label'] == $value2['label']) {
$temp[$key]['data'][] = $value['data'];
if (isset($value2['data'][$i])) {
$temp[$key]['data'][] = $value2['data'][$i];
}
} else {
$temp[$key]['data'][] = $value['data'];
if (!isset($value2['data'][$i])) {
$temp[$key]['data'][] = 0;
}
}
$i++;
}
}
echo '<pre>';
print_r($temp);
Try this out:
$array1 = array(
array(
'label' => 'pending',
'fillColor' => '#468847',
'data' => '50'
),
array(
'label' => 'dispatched',
'fillColor' => '#468847',
'data' => '10'
),
array(
'label' => 'delivered',
'fillColor' => '#468847',
'data' => '8'
),
array(
'label' => 'invoiced',
'fillColor' => '#468847',
'data' => '5'
)
);
$array2 = array(
array(
'label' => 'pending',
'fillColor' => '#468847',
'data' => array()
),
array(
'label' => 'dispatched',
'fillColor' => '#6ecf70',
'data' => array()
),
array(
'label' => 'delivered',
'fillColor' => '#f89406',
'data' => array()
),
array(
'label' => 'invoiced',
'fillColor' => '#3a87ad',
'data' => array()
)
);
foreach ($array1 as $order) {
foreach ($array2 as $key => $group) {
if ($order['label'] == $group['label']) {
array_push($array2[$key]['data'], $order['data']);
}
}
}
var_dump($array2);
Declare an array of default rows with empty data values.
Merge the default array, the first array, thrn the second array into one array.
Iterate the merged array's rows.
Declare reference arrays which are identified by label values. Explicitly cast each encountered data value as an array before joining into its group's subarray.
Code: (Demo)
$defaults = [
['label' => 'pending', 'fillColor' => '#468847', 'data' => []],
['label' => 'dispatched', 'fillColor' => '#6ecf70', 'data' => []],
['label' => 'delivered', 'fillColor' => '#f89406', 'data' => []],
['label' => 'invoiced', 'fillColor' => '#3a87ad', 'data' => []],
];
$result = [];
foreach (array_merge($defaults, $array1, $array2) as $row) {
$label = $row['label'];
$row['data'] = (array) $row['data'];
if (!isset($ref[$label])) {
$ref[$label] = $row;
$result[] = &$ref[$label];
} else {
$ref[$label]['data'] = array_merge(
$ref[$label]['data'],
$row['data']
);
}
}
var_export($result);

PHP merge associative arrays by replacing same keys and adding new

I have an array of variable size structured like this (categories is only one of the keys inside data):
print_r($json[123]["data"]["categories"]);
array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
)
print_r($json[456]["data"]["categories"]);
array(
array(
'id' => '21',
'description' => 'Downloadable Content'
),
array(
'id' => '1',
'description' => 'Multi-player'
)
)
Now, I want to merge these sub-arrays (they can be in variable number) and have all keys added and replaced. I've tried array_merge but it replaces the keys without adding new ones.
In this case I need to obtain this array:
print_r($merged["data"]["categories"]);
array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
),
array(
'id' => '21',
'description' => 'Downloadable Content'
)
)
Any help?
Edit:
I think I didn't expressed myself well enough. $json[$id]["data"] has multiple keys I want to merge (categories is just an example). Also the number of $json[$id] keys is variable
Edit2:
The arrays can have duplicate values, and the depth of the keys can be variable. I need to get something like array_merge_recursive() but with same values replaced.
Edit3:
This is the current array. http://pastebin.com/7x7KaAVM I need to merge all keys that have sub-arrays
Try below code:
$json = array(
'123' => array('data' => array('categories' => array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
))
),
'456' => array('data' => array('categories' => array(
array(
'id' => '21',
'description' => 'Downloadable Content'
)
))
),
);
//print_r($json);
$merged = array();
foreach($json as $j1)
{
foreach($j1 as $j2)
{
foreach($j2 as $key => $j3)
{
foreach($j3 as $j4)
{
$merged[$key][] = $j4;
}
}
}
}
print_r($merged);
Result:
Array
(
[categories] => Array
(
[0] => Array
(
[id] => 2
[description] => Single-player
)
[1] => Array
(
[id] => 1
[description] => Multi-player
)
[2] => Array
(
[id] => 9
[description] => Co-op
)
[3] => Array
(
[id] => 22
[description] => Steam Achievements
)
[4] => Array
(
[id] => 28
[description] => Full controller support
)
[5] => Array
(
[id] => 21
[description] => Downloadable Content
)
)
)
Demo:
http://3v4l.org/X61bE#v430
Try this . To generalize I have added some more arrays.
<?php
$merged_array = array();
$final_array = array();
$json[123]["data"]["categories"] = array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
);
$json[456]["data"]["categories"] = array(
array(
'id' => '21',
'description' => 'Downloadable Content'
)
);
$json[786]["data"]["categories"] = array(
array(
'id' => '31',
'description' => 'Downloadable Content'
)
);
$json[058]["data"]["categories"] = array(
array(
'id' => '41',
'description' => 'Downloadable Content'
)
);
foreach($json as $key=>$value){
array_push($merged_array,$json[$key]["data"]["categories"]);
}
foreach($merged_array as $value){
foreach($value as $val){
array_push($final_array,$val);
}
}
print_r($final_array);
?>
RESULT
Array
(
[0] => Array
(
[id] => 2
[description] => Single-player
)
[1] => Array
(
[id] => 1
[description] => Multi-player
)
[2] => Array
(
[id] => 9
[description] => Co-op
)
[3] => Array
(
[id] => 22
[description] => Steam Achievements
)
[4] => Array
(
[id] => 28
[description] => Full controller support
)
[5] => Array
(
[id] => 21
[description] => Downloadable Content
)
[6] => Array
(
[id] => 31
[description] => Downloadable Content
)
[7] => Array
(
[id] => 41
[description] => Downloadable Content
)
)

Comparing array against an array group

I'm trying to compare one array, against another array.
$dropship_array = array();
$dropship_query = tep_db_query("select id, email from drop_shippers");
while ($dropship = tep_db_fetch_array($dropship_query)) {
$dropship_array[] = array('id' => $dropship['id'],
'email' => $dropship['email']);
}
Now, $dropship_array[] contains:
Array (
[0] => Array (
[id] => 0
[email] => none
)
[1] => Array (
[id] => 2
[email] => dropshipper1#gmail.com
)
[2] => Array (
[id] => 5
[email] => dropshipper2#gmail.com
)
[2] => Array (
[id] => 10
[email] => dropshipper3#gmail.com
)
)
Now, I need to compare the array above (dropship_array['id']) against the array bellow (products_array['dsid']). The products_array[] array has been split so that each individual array is grouped together according to each ones [dsid]. So every time a match is found between a group of products and the drop ship id, a function needs to be performed.
$products_array = array();
$products_query = tep_db_query("select products_id, products_name, drop_ship_id from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . (int)$orders['orders_id'] . "' order by products_name");
while ($products = tep_db_fetch_array($products_query)) {
$products_array[] = array('id' => $products['products_id'],
'text' => $products['products_name'],
'dsid' => $products['drop_ship_id']);
}
Array (
[0] => Array (
[0] => Array (
[id] => 793
[text] => Gun Dog Training Book
[dsid] => 8
)
)
[1] => Array (
[0] => Array (
[id] => 789
[text] => Top Dog II Training DVD Video
[dsid] => 5
)
[1] => Array (
[id] => 237
[text] => Tri-Tronics Retriever Training Book
[dsid] => 5
)
)
)
Would this require a foreach function?
<?php
$one = array(
'0' => array(
'id' => '0',
'email' => 'none'
),
'1' => array(
'id' => '1',
'email' => 'none'
),
'2' => array(
'id' => '2',
'email' => 'none'
),
'3' => array(
'id' => '3',
'email' => 'none'
)
);
$two = array(
'0' => array(
'0' => array(
'id' => '793',
'text' => 'derp',
'dsid' => '8'
)
),
'1' => array(
'0' => array(
'id' => '793',
'text' => 'derp',
'dsid' => '8'
),
'1' => array(
'id' => '793',
'text' => 'derp',
'dsid' => '3'
)
),
);
foreach($one as $item) {
foreach($two as $compare) {
if(is_array($compare)) {
foreach($compare as $multicompare) {
if($multicompare['dsid'] == $item['id']) {
// Perform function
}
}
}
}
}
}
?>
Breaking it down:
First foreach() loops through the very first array from your drop_shippers table.
Second foreach() loops through your next array and checks if the item is an array, if so it compares the dsid with the id from the first array.

Categories