Getting multiple specific key value pairs if exist in associate array - php

I want to convert my Associate Array into array based on certain criteria:
It should contain multiple column (Hence, can't user array_column in this case.)
It should ADD duplicate date
It should remove particular sub-array if NULL. (array_filter)
Input :
array (
0 =>
array (
'date' => "2019-03-31",
'a' => '1',
'b' => '1',
),
1 =>
array (
'date' => "2019-04-02", // If "SAME" date then ADD them
'a' => '1',
'b' => '1',
),
2 =>
array (
'date' => "2019-04-02", // If "SAME" date then ADD them
'a' => '2',
'b' => '1',
),
3 =>
array (
'date' => "2019-04-10",
'a' => '', // If "NULL" then remove the particular sub-array
'b' => '1',
),
4 =>
array (
'date' => "2019-04-18",
'a' => '4',
'b' => '10',
),
)
I've tried the following,
Although I was able to select multiple column in array but this is giving me:
"Duplicate" date.
And including sub-array which has "Null" value.
function colsFromArray(array $array, $keys)
{
if (!is_array($keys)) $keys = [$keys];
return array_map(function ($el) use ($keys) {
$o = [];
foreach($keys as $key){
$o[$key] = isset($el[$key])?$el[$key]:false;
}
return $o;
}, $array);
}
$result = colsFromArray($arr, array("date", "a"));
Required Output :
array (
0 =>
array (
'date' => "2019-03-31",
'a' => '1',
),
1 =>
array (
'date' => "2019-04-02",
'a' => '3',
),
2 =>
array (
'date' => "2019-04-18",
'a' => '4',
),
)

You could try something like this:
function colsFromArray(array $array, $keys)
{
if (!is_array($keys)) $keys = [$keys];
$returnArray = [];
foreach($array as $in){
foreach($keys as $key){
//Check if the key already has a value
if(isset($returnArray[$in['date']][$key]) && is_numeric($returnArray[$in['date']][$key])){
$returnArray[$in['date']][$key] += $in[$key];
}
//If the key is empty, continue
elseif(empty($in[$key])){
continue;
}
//If value is to be set, set date as well
else{
$returnArray[$in['date']]['date'] = $in['date'];
$returnArray[$in['date']][$key] = $in[$key];
}
}
}
//Return array after resetting indexes and removing empty entries
return array_values(array_filter($returnArray));
}

The way that you are passing in the array of columns to your customer function is ambiguous about what should be used to group by and what should be summed. OR if you will never have more than two elements in your 2nd parameter, then your custom function lacks flexibility.
Notice how #SverokAdmin's answer has date hardcoded in the logic, but there is no guarantee that this column name will always exist in the first parameter $array. Ergo, the utility function cannot be reliably used as a utility function.
Consider this custom function which provides your desired result, but allows more meaningful parameter declarations. My snippet allows you to group by one or more column, keep one or more columns in the subarrays, and specify which column should be summed. I cannot make the last column iterable because you state that if a column is missing a value, it should be omitted from the result. In other words, your desired result is unknown if you wanted to sum a and b, but one of the a values was empty.
Code: (Demo)
function colsFromArray(array $array, $groupBy, $keepables, $summable): array
{
$groupBy = (array)$groupBy;
$keepables = (array)$keepables;
// cannot make $summable iterable type because question is unclear on the desired outcome when one of the columns is empty
return array_values(
array_reduce(
$array,
function ($result, $row) use($groupBy, $keepables, $summable) {
$uniqueKey = [];
foreach ($groupBy as $col) {
$uniqueKey[] = $row[$col];
}
$uniqueKey = implode('_', $uniqueKey);
if (!$row[$summable]) {
return $result;
}
foreach ($keepables as $keepable) {
$result[$uniqueKey][$keepable] = $row[$keepable];
}
$result[$uniqueKey][$summable] = ($result[$uniqueKey][$summable] ?? 0) + $row[$summable];
return $result;
},
[]
)
);
}
var_export(
colsFromArray($arr, 'date', 'date', 'a')
);
Output:
array (
0 =>
array (
'date' => '2019-03-31',
'a' => 1,
),
1 =>
array (
'date' => '2019-04-02',
'a' => 3,
),
2 =>
array (
'date' => '2019-04-18',
'a' => 4,
),
)

Related

How can I check and delete duplicate arrays?

how can I check and delete duplicate arrays?
Example:
$a = array(
array(
'id' => 1,
'name' => 'test'
),
// Next array is equal to first, then delete
array(
'id' => 1,
'name' => 'test'
),
// Different array, then continue here
array(
'id' => 2,
'name' => 'other'
)
);
If the array is the same, then delete the duplicate and get only one array.
You can use a lookup table storing serialized arrays. If an array already exists in the lookup table, you have a duplicate and can splice out the key:
$a = array(
array(
'id' => 1,
'name' => 'test'
),
array(
'id' => 1,
'name' => 'test'
),
array(
'id' => 2,
'name' => 'other'
)
);
$seen = [];
for ($i = count($a) - 1; $i >= 0; $i--) {
if (array_key_exists(json_encode($a[$i]), $seen)) {
array_splice($a, $i, 1);
}
else {
$seen[json_encode($a[$i])] = 1;
}
}
print_r($a);
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => test
)
[1] => Array
(
[id] => 2
[name] => other
)
)
Try it!
array_unique()
Example:
$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
You can loop through the parent array, serialize each child array and save it in a third array, and as you are looping, check for the existence of the serial of each next child array to all previous ones saved in the third array. If it exists, remove the current duplicate from the parent array by key. The function below demonstrates this.
function remove_duplicate_nested_arrays($parent_array)
$temporary_array = array(); // declare third, temporary array.
foreach($parent_array as $key => $child_array){ // loop through parent array
$child_array_serial = serialize($child_array); // serialize child each array
if(in_array($child_array_serial,$temporary_array)){ // check if child array serial exists in third array
unset($parent_array[$key]); // unset the child array by key from parent array if it's serial exists in third array
continue;
}
$temporary_array[] = $child_array_serial; // if this point is reached, the serial of child array is not in third array, so add it so duplicates can be detected in future iterations.
}
return $parent_array;
}
This can also be achieved in 1 line, using #Jose Carlos Gp suggestion as follows:
$b = array_map('unserialize', array_unique(array_map('serialize', $a)));
The function above kind of expands on what is actually happening in the 1 liner solution.

How to check if duplicate values of some indexes exist in multi dimensional array or not?

My problem is i have a multidimensional array posting from form to php, now i want to checking if duplicate values of some indexes exist in multi dimensional array or not?
e.g:
$data=Array
(
0 => Array
(
uid => '100',
name => 'Sandra Shush',
type => 'abc'
),
1 => Array
(
uid => '101',
name => 'Sandra Shushtext',
type => 'xyz'
),
2 => Array
(
uid => '100',
name => 'Sandra Shush',
type => 'abc'
)
);
here name and type of index 1 and 2 are same, so how can i check it?
I am familiar with
$key = array_search('abc', array_column($data, 'type'));
but it is for duplication of single column value in multi rows, in my situation if multi column of same rows same with multi column of any other row then record will be consider as duplicate.
Any help should be appreciated, Thanks in advance.
You can try using array_reduce by creating a key using your desired item keys:
$result = array_reduce($data, function ($carry, $item) {
$key = $item['uid'] . $item['type'];
$item['is_duplicate'] = isset($carry[$key]);
if ($item['is_duplicate']) {
$carry[] = $item;
} else {
$carry[$key] = $item;
}
return $carry;
}, []);
var_dump($result);
The easiest way, well at least the one I would use is to encode your arrays into md5 (or any other kind) string and compare those values. I think it is the most efficient in your case.
Example:
<?php
function arrayToString($array) {
$str = '';
if ( !is_array($array) )
return $str;
foreach ( $array as $key => $val ) {
$str .= $key . ':' . $val;
}
return $str;
}
$data=Array
(
0 => Array
(
'uid' => '100',
'name' => 'Sandra Shush',
'type' => 'abc'
),
1 => Array
(
'uid' => '100',
'name' => 'Sandra Shush',
'type' => 'xyz'
),
2 => Array
(
'uid' => '100',
'name' => 'Sandra Shush',
'type' => 'abc'
)
);
$temp = array();
foreach ( $data as $d ) {
array_push($temp, md5(arrayToString($d)));
}
$unique = array_unique($temp);
var_dump($unique); // prints unique array
This is a very fast designed approach and will find duplicates. Note that duplicates are elements which have the same value for the same key. So if any of uid, name or type match, they will be treated as duplicates. Therefore I adjust the third array element, because all elements in your array share the same values.
$data = [
....
2 =>
[
'uid' => '200',
'name' => 'Mandra Shush',
'type' => 'abcx'
]
];
$duplicates = [];
$valuesToCompare = ["uid", "name", "type"];
function equals($value, $toCompare, $keysToCompare)
{
foreach ($keysToCompare as $compareKey) {
if ($value[$compareKey] === $toCompare[$compareKey]) {
return true;
}
}
return false;
}
foreach ($data as $index => $element) {
foreach ($data as $indexInner => $elementToCompare) {
if ($index !== $indexInner) {
if (equals($element, $elementToCompare, $valuesToCompare)) {
$duplicates[] = [$index => $indexInner];
}
}
}
}
var_dump($duplicates);
This will output the following, which indicates we found 2 duplicates. Where element 0 is duplicate of 1, and 1 is duplicate of 0.
array (size=2)
0 =>
array (size=1)
0 => int 1
1 =>
array (size=1)
1 => int 0
I achieved above scenario like this:
Dont know which one is best mine or other's who posted answers.
foreach($data as $key => $row)
{
$combinedarr[] = array("name"=>$row["name"],"type"=>$row["type"]);
}
//chck if same facilitiy is being visit on same date twice
$countcomb = count($combinedarr);
$uniquearr = array_unique($combinedarr, SORT_REGULAR);
if($countcomb==count($uniquearr)){
}else{
//yes duplicate exists
};
Thanks again for those who answered.

Multidimensional Array - Match by odd key

I am trying to find the difference of 2 multidimensional arrays. I am attempting to solve this with a modified recursive array difference function.
If I have the following array setup:
$array1 = array(
0 => array(
'Age' => '1004',
'Name' => 'Jack'
),
1 => array (
'Age' => '1005',
'Name' => 'John'
)
);
$array2 = array(
0 => array(
'Age_In_Days' => '1004',
'Name' => 'Jack'
),
1=> array(
'Transaction_Reference' => '1005',
'Name' => 'Jack'
)
);
I am trying to match the arrays however the keys are not the same. I want to return the difference between the two multidimensional arrays where
$array1[$i]['Age'] == $array2[$i]['Age_In_Days'];
I want to keep the original array structure if the above condition holds true so the output I am looking for is:
$diff = array (1 => array (
'Age' => '1005',
'Name' => 'John'
));
However I am having issues with how to modify the recursive function to achieve this. Any help is appreciated! Thanks!
You need to loop through first array and compare values with second array. Then follows your condition. If condition is true then push this unique value to third array. Values in third array are now diff between first and second array.
$diff = [];
foreach ($array1 as $value1) {
foreach ($array2 as $value2) {
if ($value1['Age'] !== $value2['Age_In_Days']) {
array_push($diff, $value1);
}
}
}

Get key of multidimensional array?

For example, I have multidimensional array as below:
$array = array (
0 =>
array (
'id' => '9',
'gallery_id' => '2',
'picture' => '56475832.jpg'
),
1 =>
array (
'id' => '8',
'gallery_id' => '2',
'picture' => '20083622.jpg'
),
2 =>
array (
'id' => '7',
'gallery_id' => '2',
'picture' => '89001465.jpg'
),
3 =>
array (
'id' => '6',
'gallery_id' => '2',
'picture' => '47360232.jpg'
),
4 =>
array (
'id' => '5',
'gallery_id' => '2',
'picture' => '4876713.jpg'
),
5 =>
array (
'id' => '4',
'gallery_id' => '2',
'picture' => '5447392.jpg'
),
6 =>
array (
'id' => '3',
'gallery_id' => '2',
'picture' => '95117187.jpg'
)
);
How can I get key of array(0,1,2,3,4,5,6)?
I have tried a lot of examples, but nothing has worked for me.
This is quite simple, you just need to use array_keys():
$keys = array_keys($array);
See it working
EDIT For your search task, this function should do the job:
function array_search_inner ($array, $attr, $val, $strict = FALSE) {
// Error is input array is not an array
if (!is_array($array)) return FALSE;
// Loop the array
foreach ($array as $key => $inner) {
// Error if inner item is not an array (you may want to remove this line)
if (!is_array($inner)) return FALSE;
// Skip entries where search key is not present
if (!isset($inner[$attr])) continue;
if ($strict) {
// Strict typing
if ($inner[$attr] === $val) return $key;
} else {
// Loose typing
if ($inner[$attr] == $val) return $key;
}
}
// We didn't find it
return NULL;
}
// Example usage
$key = array_search_inner($array, 'id', 9);
The fourth parameter $strict, if TRUE, will use strict type comparisons. So 9 will not work, you would have to pass '9', since the values are stored as strings. Returns the key of the first occurence of a match, NULL if the value is not found, or FALSE on error. make sure to use a strict comparison on the return value, since 0, NULL and FALSE are all possible return values and they will all evaluate to 0 if using loose integer comparisons.
Try this , I think it will help you.
foreach ($array as $key=>$value)
{
echo $key.'<br/>';
echo $value['id'].'<br/>';
echo $value['gallery_id'].'<br/>';
echo $value['picture'].'<br/><br/>';
}
sometimes it is to easy to find ;)
array_keys($array);
array_keys
Probably http://php.net/manual/en/function.array-keys.php ?
Convert your double dimensional array on your own:
$tmp = null
foreach($array as $key => $value) {
$tmp[] = $key;
}
print_r($tmp);
You mean something like this:
function getKeys($array)
{
$resultArr = array();
foreach($array as $subArr) {
$resultArr = array_merge($resultArr, $subArr);
}
return array_keys($resultArr);
}

Matching an array value by key in PHP

I have an array of items:
array(
[0] => array(
'item_no' => 1
'item_name' => 'foo
)
[1] => array(
'item_no' => 2
'item_name' => 'bar'
)
) etc. etc.
I am getting another array from a third party source and need to remove items that are not in my first array.
array(
[0] => array(
'item_no' => 1
)
[1] => array(
'item_no' => 100
) # should be removed as not in 1st array
How would I search the first array using each item in the second array like (in pseudo code):
if 'item_no' == x is in 1st array continue else remove it from 2nd array.
// Returns the item_no of an element
function get_item_no($arr) { return $arr['item_no']; }
// Arrays of the form "item_no => position in the array"
$myKeys = array_flip(array_map('get_item_no', $myArray));
$theirKeys = array_flip(array_map('get_item_no', $theirArray));
// the part of $theirKeys that has an item_no that's also in $myKeys
$validKeys = array_key_intersect($theirKeys, $myKeys);
// Array of the form "position in the array => item_no"
$validPos = array_flip($validKeys);
// The part of $theirArray that matches the positions in $validPos
$keptData = array_key_intersect($theirArray, $validPos);
// Reindex the remaining values from 0 to count() - 1
return array_values($keptData);
All of this would be easier if, instead of storing the key in the elements, you stored it as the array key (that is, you'd be using arrays of the form "item_no => item_data") :
// That's all there is to it
return array_key_intersect($theirArray, $myArray);
You can also do:
$my_array =array(
0 => array( 'item_no' => 1,'item_name' => 'foo'),
1 => array( 'item_no' => 2,'item_name' => 'bar')
);
$thrid_party_array = array(
0 => array( 'item_no' => 1),
1 => array( 'item_no' => 100),
);
$temp = array(); // create a temp array to hold just the item_no
foreach($my_array as $key => $val) {
$temp[] = $val['item_no'];
}
// now delete those entries which are not in temp array.
foreach($thrid_party_array as $key => $val) {
if(!in_array($val['item_no'],$temp)) {
unset($thrid_party_array[$key]);
}
}
Working link
If your key is not actually a key of your array but a value, you will probably need to do a linear search:
foreach ($itemsToRemove as $itemToRemove) {
foreach ($availableItems as $key => $availableItem) {
if ($itemToRemove['item_no'] === $availableItem['item_no']) {
unset($availableItems[$key]);
}
}
}
It would certainly be easier if item_no is also the key of the array items like:
$availableItems = array(
123 => array(
'item_no' => 123,
'item_name' => 'foo'
),
456 => array(
'item_no' => 456,
'item_name' => 'bar'
)
);
With this you could use a single foreach and delete the items by their keys:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$itemToRemove['item_no']]);
}
You could use the following to build an mapping of item_no to your actual array keys:
$map = array();
foreach ($availableItems as $key => $availableItem) {
$map[$availableItems['item_no']] = $key;
}
Then you can use the following to use the mapping to delete the corresponding array item:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$map[$itemToRemove['item_no']]]);
}

Categories