Combining arrays based on keys from another array - php

I want to combine two arrays like this:
1st array:
array( "ATTENDED" => 1,
"TENTATIVE" => 2, //
"REJECTED" => 3,
"OUTSTANDING" => 4,
"ACCEPTED" => 6
);
2nd Array:
array ( 1 => 29,
4 => 30,
6 => 47
);
I want to get the results like this:
array ( 'ATTENDED' => 29,
'OUTSTANDING' => 30,
'ACCEPTED' => 47
);
2nd array is flexible. I can flip keys and values.
or better yet:
array( "ATTENDED" => 29,
"TENTATIVE" => 0, //
"REJECTED" => 0,
"OUTSTANDING" => 30,
"ACCEPTED" => 47
);
I know there must be a simple solution.
Any ideas?

foreach ($arr1 as $k1 => $v1) {
$arr1[$k1] = isset($arr2[$v1]) ? $arr2[$v1] : 0;
}
edit-
This is without an explicit loop, although I don't think this is really better, but maybe cooler though.
$mapped = array_map(function($valFromArr1) use ($arr2) {
return isset($arr2[$valFromArr1]) ? $arr2[$valFromArr1] : 0;
}, $arr1);
I can't think of a sane way to just use pure php functions.

$labels = array(
"ATTENDED" => 1,
"TENTATIVE" => 2,
"REJECTED" => 3,
"OUTSTANDING" => 4,
"ACCEPTED" => 6
);
$values = array(
1 => 29,
4 => 30,
6 => 47
);
$results = array();
foreach ($labels as $label => $id) {
$results[$label] = array_key_exists($id, $values) ? $values[$id] : 0;
}

Related

array_diff with calculation

Please, consider the following arrays:
$reference = array(
'080604' => 4,
'080703' => 4,
'080734' => 2,
'080819' => 2,
'088341' => 2,
'805238' => 20,
'805283' => 4,
'805290' => 2,
'805849' => 2,
'806051' => 2,
'806068' => 2,
);
$test = array(
'080604' => 2,
'080703' => 4,
'080819' => 1,
'088341' => 2,
'805238' => 20,
'805283' => 4,
'805290' => 2,
'805849' => 2,
'806051' => 2,
'806068' => 2,
);
They are quite similar, but can have some various differences, e.g. it's possible that:
- some keys of $reference are not present in $test at all
- some keys of $test are not present in $reference at all
- all keys are present, but the values in $reference and $test are different (sometimes $reference value is bigger than $test and sometimes the value of $test is bigger than $reference)
I need to find out the differences automatically and to output them in a way, that not only the difference in count itself, but also a description is provided, e.g.
$result = [
'080604' => [
'reference' => 4,
'test' => 2
]
];
If some value is in only one of the lists:
$result = [
'1234567890' => [
'reference' => 0,
'test' => 2
]
];
or something like that.
Does someone have an idea, which is the best way to accomplish this in an elegant way? Thank you very much!
Iterate over each and populate the array with values if present:
$combined = [];
foreach ($reference as $key => $val) {
$combined[$key] = [
'test' => 0,
'reference' => $val,
];
}
foreach ($test as $key => $val) {
if (!isset($combined[$key])) {
$combined[$key] = [
'reference' => 0,
'test' => 0,
]
}
$combined[$key]['test'] = $val;
}
$combined will contain both values from both arrays with reference to both the elements from $reference and $test.
try
$result = array_diff($reference, $test);
print_r($result)

Reformat array without temp variable

I have the next array
[
['id' => 30, 'count' => 3],
['id' => 45, 'count' => 7]
]
I need it to be
[
30 => ['count' => 3],
45 => ['count' => 7]
]
What I did
$formatted = [];
foreach ($services as $service) {
$formatted[$service['id']] = [
'count' => $service['count']
];
}
What I'd like is a more elegant solution without the temporary $formatted variable. Thanks!
Update. Thanks a lot #rtrigoso !
With the laravel collection, my code looks next
$services->reduce(function ($carry, $item) {
$carry[$item['id']] = ['count' => $item['count']];
return $carry;
});
You can do this in one line with array_column:
$array = array_column($array, null, 'id');
The one difference between your desired output is that this will still contain the id key in the second level of the array, like so:
[
30 => ['id' => 30, 'count' => 3],
45 => ['id' => 45, 'count' => 7],
]
but that hopefully shouldn't cause any problems. If you do need to remove it, you can do it with something like:
$array = array_map(function ($e) {
unset($e['id']);
return $e;
}, $array);
This approach is probably best if your rows could potentially have a lot more keys in them in future, i.e. it's quicker to list the keys to remove rather than the ones to keep. If not, and you'll only have a count, then to be honest your original example is probably the best you'll get.
You can use array_reduce
$x_arr = array(
array('id' => 30, 'count' => 3),
array('id' => 45, 'count' => 7),
);
$y_arr = array_reduce($x_arr, function ($result, $item) {
$result[$item['id']] = array('count' => $item['count']);
return $result;
}, array());
print_r($y_arr);
It will give you your desired result:
Array
(
[30] => Array
(
[count] => 3
)
[45] => Array
(
[count] => 7
)
)

Sort an multidimensional array per string from array [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I've got an multidimensional array which is build like this:
array(
array(
'zahlungen_id' => 1,
'reise_id' => 1,
'name' => 'Liam Schnell',
'schul_id' => 1,
'summe' => 49,
'art' => 'PayPal',
'sicher' => 0,
'datum' => '2014-05-05'
),
array(
'zahlungen_id' => 2,
'reise_id' => 3,
'name' => 'Max Göllner',
'schul_id' => 1,
'summe' => 49,
'art' => 'SOFORT',
'sicher' => 1,
'datum' => '2014-05-06'
),
array(
'zahlungen_id' => 3,
'reise_id' => 2,
'name' => 'Sasha Novalja',
'schul_id' => 2,
'summe' => 49,
'art' => 'Kreditkarte',
'sicher' => 1,
'datum' => '2014-05-05'
),
array(
'zahlungen_id' => 4,
'reise_id' => 1,
'name' => 'Hans Wurst',
'schul_id' => 1,
'summe' => 49,
'art' => 'Sofort',
'sicher' => 0,
'datum' => '2014-05-04'
)
);
Is there any way I can use 'schul_id' to sort the array itself? Like a descending schul_id?
array_multisort covers this, here's a sample from their docs tweaked to your question:
foreach($data as $key => $row) {
$schul_id[$key] = $row['schul_id'];
}
array_multisort($schul_id, SORT_DESC, $data);
print_r($data);
First comment was right! I used this one
function aasort(&$array, $key) {
$sorter = array();
$ret = array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii] = $va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii] = $array[$ii];
}
$array = $ret;
}
You are looking for uasort:
function cmp($a, $b) {
if ($a["schul_id"] == $b["schul_id"]) {
return 0;
}
return ($a["schul_id"] > $b["schul_id"]) ? -1 : 1;
}
uasort($array, 'cmp');

How can I add a $key=>$value pair to an associative array using a foreach loop in PHP?

I have two associative arrays I wish to combine with a foreach loop:
$arr1 = array( 'wikipedia.org' => 11, 'bing.com' => 9, 'google.com' => 8, 'blekko.com' => 7, 'groove.com' => 6, 'blo.com' => 5, 'ekko.com' => 4, 'rokko.com' => 3, 'always.com' => 2, 'popo.com' => 1);
$arr2 = array( 'google.com' => 20, 'blekko.com' => 19, 'wikipedia.org' => 8, 'bing.com' => 7, 'blo.com' => 6, 'ekko.com' => 5, 'groove.com' => 4, 'popo.com' => 3, 'always.com' => 2, 'rokko.com' => 1);
I use a new array
$combined = $arr1;
with a foreach loop
foreach($arr2 as $key=>$value)
{
array_push($combined,$value);
}
... which adds the value but not the key. I think I know why, but cannot find a way to add the key and the value. This works for a single line, but frustratingly nor in a foreach loop!
$combined=array_merge(array('blovk.com'=>'44'),$combined);
$aggregatedResults[$key] = $value;
It should be that simple...

In PHP, is there a function that returns an array made up of the value of a key from an array of associative arrays? [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed last month.
I'm sure this question has been asked before, my apologies for not finding it first.
The original array:
[0] => Array
(
[categoryId] => 1
[eventId] => 2
[eventName] => 3
[vendorName] => 4
)
[1] => Array
(
[categoryId] => 5
[eventId] => 6
[eventName] => 7
[vendorName] => 8
)
[2] => Array
(
[categoryId] => 9
[eventId] => 10
[eventName] => 11
[vendorName] => 12
)
My hoped for result out of: print_r(get_values_from_a_key_in_arrays('categoryId', $array));
[0] => 1
[1] => 5
[2] => 9
I'm just looking for something cleaner than writing my own foreach based function. If foreach is the answer, I already have that in place.
Edit: I don't want to use a hard-coded key, I was just showing an example call to the solution. Thanks! ^_^
Quick Grab Solution for PHP 5.3:
private function pluck($key, $data) {
return array_reduce($data, function($result, $array) use($key) {
isset($array[$key]) && $result[] = $array[$key];
return $result;
}, array());
}
So, the cool thing about higher-order collection/iterator functions such as pluck, filter, each, map, and friends is that they can be mixed and matched to compose a more complex set of operations.
Most languages provide these types of functions (look for packages like collection, iterator, or enumeration/enumerable)...some provide more functions than others and you will commonly see that the functions are named differently across languages (i.e. collect == map, reduce == fold). If a function doesn't exist in your language, you can create it from the ones that do exist.
As for your test case...we can use array_reduce to implement pluck. The first version I posted relied on array_map; however, I agree with #salathe that array_reduce is more succinct for this task; array_map is an OK option, but you end up having to do more work in the end. array_reduce can look a bit odd at first, but if the callback is neatly organized, all is well.
A less naive pluck would also check to see if it can "call" (a function/method) on the iterated value. In the naive implementation below, we assume the structure to be a hash (associative array).
This will setup the test-case data (Fixtures):
<?php
$data[] = array('categoryId' => 1, 'eventId' => 2, 'eventName' => 3, 'vendorName' => 4);
$data[] = array('categoryId' => 5, 'eventId' => 6, 'eventName' => 7, 'vendorName' => 8);
$data[] = array('categoryId' => 9, 'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array(/* no categoryId */ 'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array('categoryId' => false,'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array('categoryId' => 0.0, 'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
Choose the version of pluck you'd prefer
$preferredPluck = 'pluck_array_reduce'; // or pluck_array_map
"pluck" for PHP 5.3+: array_reduce provides a terse implementation though not as easy to reason about as the array_map version:
function pluck_array_reduce($key, $data) {
return array_reduce($data, function($result, $array) use($key){
isset($array[$key]) &&
$result[] = $array[$key];
return $result;
}, array());
}
"pluck" for PHP 5.3+: array_map isn't perfect for this so we have to do more checking (and it still doesn't account for many potential cases):
function pluck_array_map($key, $data) {
$map = array_map(function($array) use($key){
return isset($array[$key]) ? $array[$key] : null;
}, $data);
// is_scalar isn't perfect; to make this right for you, you may have to adjust
return array_filter($map, 'is_scalar');
}
"pluck" for legacy PHP <5.3
We could have used the legacy create_function; however, it is bad form, not recommended, and also not at all elegant, thus, I've decided not to show it.
function pluck_compat($key, $data) {
$map = array();
foreach ($data as $array) {
if (array_key_exists($key, $array)) {
$map[] = $array[$key];
}
}
unset($array);
return $map;
}
Here we choose a version of "pluck" to call based on the version of PHP we are running. If you run the entire script, you should get the correct answer no matter what version you are on.
$actual = version_compare(PHP_VERSION, '5.3.0', '>=')
? $preferredPluck('categoryId', $data)
: pluck_compat('categoryId', $data);
$expected = array(1, 5, 9, false, 0.0);
$variance = count(array_diff($expected, $actual));
var_dump($expected, $actual);
echo PHP_EOL;
echo 'variance: ', $variance, PHP_EOL;
print #assert($variance)
? 'Assertion Failed'
: 'Assertion Passed';
Notice there is no ending '?>'. That is because it isn't needed. More good can come of leaving it off than from keeping it around.
FWIW, it looks like this is being added to PHP 5.5 as array_column.
Mapping is what you need:
$input = array(
array(
'categoryId' => 1,
'eventId' => 2,
'eventName' => 3,
'vendorName' => 4,
),
array(
'categoryId' => 5,
'eventId' => 6,
'eventName' => 7,
'vendorName' => 8,
),
array(
'categoryId' => 9,
'eventId' => 10,
'eventName' => 11,
'vendorName' => 12,
),
);
$result = array_map(function($val){
return $val['categoryId'];
}, $input);
Or creating a function you wanted:
function get_values_from_a_key_in_arrays($key, $input){
return array_map(function($val) use ($key) {
return $val[$key];
}, $input);
};
and then using it:
$result = get_values_from_a_key_in_arrays('categoryId', $array);
It will work in PHP >= 5.3, where anonymous callbacks are allowed. For earlier versions you will need to define callback earlier and pass its name instead of anonymous function.
There's no built-in function for this, but it's usually referred as "pluck".
<?php
$a = array(
array('a' => 1, 'b' => 2),
array('a' => 2, 'b' => 2),
array('a' => 3, 'b' => 2),
array('a' => 4, 'b' => 2)
);
function get_a($v) {
return $v['a'];
}
var_dump(array_map('get_a', $a));
You can use an create_function or an anonymous function (PHP 5.3 >=)
<?php
$a = array(
array('a' => 1, 'b' => 2),
array('a' => 2, 'b' => 2),
array('a' => 3, 'b' => 2),
array('a' => 4, 'b' => 2)
);
var_dump(array_map(create_function('$v', 'return $v["a"];'), $a));
I'd write a callback function, as above, and then use it with array_map.
As of PHP 5.5, use array_column:
$events = [
[ 'categoryId' => 1, 'eventId' => 2, 'eventName' => 3, 'vendorName' => 4 ],
[ 'categoryId' => 5, 'eventId' => 6, 'eventName' => 7, 'vendorName' => 8 ],
[ 'categoryId' => 9, 'eventId' => 10, 'eventName' => 11, 'vendorName' => 12 ],
];
print_r(array_column($events, 'categoryId'));
See it online at 3v4l.
For versions before 5.5, you may consider using a polyfill.
There's no built in function. But one is easily made with array_map().
$array = array(
array(
"categoryID" => 1,
"CategoryName" => 2,
"EventName" => 3,
"VendorName" => 4
),
array(
"categoryID" => 5,
"CategoryName" => 6,
"EventName" => 7,
"VendorName" => 8
),
array(
"categoryID" => 9,
"CategoryName" => 10,
"EventName" => 11,
"VendorName" => 12
)
);
$newArray = array_map(function($el) {
return $el["categoryID"];
}, $array);
var_dump($newArray);
Where is lisp when you need it? Actually in php it is pretty easy to manage too. Just use the array_map function as illustrated below.
# bunch o data
$data = array();
$data[0] = array("id" => 100, "name" => 'ted');
$data[1] = array("id" => 200, "name" => 'mac');
$data[2] = array("id" => 204, "name" => 'bub');
# what you want to do to each bit of it
function pick($n) { return($n['id']); }
# what you get after you do that
$map = array_map("pick", $data);
# see for yourself
print_r($map);
You could use array_filter, and pass in a function based on the desired key.
Tadeck's answer is way better though.

Categories