De duplicate multidimensional array - php

I have a fairly simple multidimensional array that I need to dedupe. I also need to remove any key that has a value, so in the below code I would need to keep the second target/value of city/Paris (Array 3) and also remove the 6th Array.
Array
(
[0] => Array
(
[target] => city
[value] => London
)
[1] => Array
(
[target] => colour
[value] => Red
)
[3] => Array
(
[target] => city
[value] => Paris
)
[4] => Array
(
[target] => type
[value] => House
)
[6] => Array
(
[target] => name
[value] =>
)
[7] => Array
(
[target] => email
[value] => mail#gmail.com
)
[9] => Array
(
[target] => custom2
[value] => path/to/something
)
)
I can do this by:
Flattening the array
Assigning the target/value as new key/values (this automatically overwrites the later value if there are dupes)
Remove any keys that have a value of
Rebuild the array
This feels wrong and I'm sure there is a better solution using array_walk_recursive() as this would probably preserve the original keys and make for a more elegant solution.
This is my current code:
function _clean_and_dedupe_targeting($array) {
// First flatten the array.
$flattenned = array();
foreach ($array as $item) {
foreach ($item as $value) {
$flattenned[] = $value;
}
}
// Take alternate items as key/value pairs.
// THIS WILL OVERWRITE ANY DUPLICATES LEAVING THE ONE SET IN CONTEXT IN PLACE.
$keyval = array();
array_unshift($flatenned, false);
while (false !== $key = next($flattenned)) {
$keyval[$key] = next($flattenned);
}
// Remove any items with <REMOVE>
$remove_string = '<REMOVE>';
$remove_keys = array_keys($keyval, $remove_string);
// Remove any keys that were found.
foreach ($remove_keys as $key) {
unset($keyval[$key]);
}
// Rebuild the array as a multidimensional array to send to the js.
$targeting = array();
$i = 0;
foreach ($keyval as $target => $value) {
$targeting[$i] = array('target' => $target, 'value' => $value);
$i++;
}
return $targeting;
}

Your algorithm is exactly what you would do:
// flatten and remove empty values
$params = array();
foreach ($values as $value) {
if (!empty($value['value'])) {
$params[$value['target']] = $value['value'];
}
}
// rebuild array
$values = array();
foreach ($params as $target => $value) {
$values[] = array(
'target' => $target,
'value' => $value,
);
}

Related

php merge arrays and change its grouping [duplicate]

I have a multidimensional array and am trying to group them according to the value in a specific column.
I'm trying to group them by level, but I won't actually know the level beforehand. So, it's not like I can put it in a for loop and say while $i < 7, because I won't know that 7 is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did.
[
['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]
Desired result:
Array (
[1] => Array (
[0] => Array (
[cust] => XT8900
[type] => standard
)
[1] => Array (
[cust] => XT8944
[type] => standard
)
)
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
)
Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.
If not then build a temporary array to sort:
foreach ($input_arr as $key => &$entry) {
$level_arr[$entry['level']][$key] = $entry;
}
Leaves you with the form you wanted and everything referenced together.
Build the array like that in the first place though if at all possible.
You need to group them by level first
Use foreach to loop into array check if the level is the same with the previous item then group it with that array
$templevel=0;
$newkey=0;
$grouparr[$templevel]="";
foreach ($items as $key => $val) {
if ($templevel==$val['level']){
$grouparr[$templevel][$newkey]=$val;
} else {
$grouparr[$val['level']][$newkey]=$val;
}
$newkey++;
}
print($grouparr);
The output of print($grouparr); will display like the format you hoped for
You can also try to
print($grouparr[7]);
Will display
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
Or
print($grouparr[3]);
Will display
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
Here is the solution I landed on for an identical problem, wrapped as a function:
function arraySort($input,$sortkey){
foreach ($input as $key=>$val) $output[$val[$sortkey]][]=$val;
return $output;
}
To sort $myarray by the key named "level" just do this:
$myArray = arraySort($myArray,'level');
Or if you didn't want it as a function, just for a one time use, this would create $myNewArray from $myArray grouped by the key 'level'
foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val;
function group_assoc($array, $key) {
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
return $return;
}
//Group the requests by their account_id
$account_requests = group_assoc($requests, 'account_id');
$result = array();
foreach ($yourArrayList as $data) {
$id = $data['level'];
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
Best ans.
$levels = array_unique(array_column($records, 'level'));
$data = array();
foreach($records as $key => $value){
$data[$levels[array_search($value['level'],$levels )]][] = $value ;
}
print_r($data);
To generate the question's exact desured output from the sample input, pull/pop the last value from each row, use that value as the first level grouping key. Then use the original first level index as the second level key. Then push the two remaining elements into the group's subset.
Code: (Demo)
$result = [];
foreach ($array as $key => $row) {
$result[array_pop($row)][$key] = $row;
}
var_export($result);
For functional style syntax, use array_reduce(). (Demo)
var_export(
array_reduce(
array_keys($array),
function($result, $key) use ($array) {
$result[array_pop($array[$key])][$key] = $array[$key];
return $result;
}
)
);
function _group_by($array,$key,$keyName)
{
$return = array();
foreach($array as $val) {
$return[$keyName.$val[$key]][] = $val;
}
return $return;
} //end of function

Replace empty entry with previous element in associative array

I have following $data array
Array
(
[0] => Array
(
[match_day] => MD27
[price] => 95.33
)
[1] => Array
(
[match_day] => MD28
[price] => 97.82
)
[2] => Array
(
[match_day] => MD29
[price] =>
)
[3] => Array
(
[match_day] => MD30
[price] =>
)
[4] => Array
(
[match_day] => MD31
[price] =>
)
)
Now, my requirements is - replace empty entry of price attribute with previous price attribute.
No need to go for for loop You can try following code:
$result = [];
array_walk($data, function($v,$k) use (&$result){
$result[$k] = $v;
if(!isset($result[$k]['price']) || $result[$k]['price'] == null){
$result[$k]['price'] = $result[$k - 1]['price'];
}
});
print_r($result);
Working Demo is Here
Perform a foreach loop an your array, store previous price value and if the current item has empty price, use previous to replace it. Example:
$previous = 0;
foreach($data AS $key => $row) {
if (empty($row['price']))
$data[$key]['price'] = $previous;
else
$previous = $row['price'];
}

Creating an array from a string issue

I have a function that creates a multi-dimensional array from a string. Here's how the output looks like for each string:
Strings:
app.name.version
app.vendor
NOTE: These are strings that are being retrieved from a database
Output:
['app']['name']['version']
['app']['vendor']
and I assign them values accordingly. The problem arises when I include numbers in the string representing an index number of a sub array. Here's an example:
shifts.breaks.unpaid.0.description
shifts.breaks.unpaid.0.duration
shifts.breaks.unpaid.1.description
shifts.breaks.unpaid.1.duration
with output:
Array
(
[unpaid] => Array
(
[0] => Array
(
[description] => Lunch
)
[1] => Array
(
[duration] => 30
)
[3] => Array
(
[description] => Lunch 2
)
[4] => Array
(
[duration] => 30
)
)
)
Where it should normally look like:
Array
(
[unpaid] => Array
(
[0] => Array
(
[description] => Lunch
[duration] => 30
)
[1] => Array
(
[description] => Lunch 2
[duration] => 30
)
)
)
The only thing that remedies this is if I replace the numbers with anything but numerical values like the following:
shifts.breaks.unpaid.b0.description
shifts.breaks.unpaid.b0.duration
shifts.breaks.unpaid.b1.description
shifts.breaks.unpaid.b1.duration
Array
(
[unpaid] => Array
(
[b0] => Array
(
[description] => Lunch
[duration] => 30
)
[b1] => Array
(
[description] => Lunch 2
[duration] => 30
)
)
)
Here's the function that creates the arrays:
function toArray($keys, $value){
$array = array();
$ref = &$array;
while(count($keys) > 0){
$n = array_shift($keys);
if(!is_array($ref))
$ref = array();
$ref = &$ref[$n];
}
$ref = $value;
return $array;
}
Where $keys contains $keys = explode('.', "my.testing.string"); and here's the example I've been working with:
$strings = array (
"app.names.0.first"=> "Samuel",
"app.names.0.last"=> "Smith",
"app.names.1.first" => "Mary",
"app.names.2.last" =>"Kubik"
);
$list = array();
foreach($strings as $key => $name) {
$list[] = (toArray(explode('.', $key),$name));
}
print_r(call_user_func_array('array_merge_recursive', $list));
At this point, I'm not too sure if this has something to do with array_merge_recursive. Any help in correcting this would be great!
Well one solution I found was re-writing a new array_merge_recursive function without overwriting numeric keys.
function array_merge_recursive_new() {
$arrays = func_get_args();
$base = array_shift($arrays);
foreach ($arrays as $array) {
reset($base); //important
while (list($key, $value) = #each($array)) {
if (is_array($value) && #is_array($base[$key])) {
$base[$key] = array_merge_recursive_new($base[$key], $value);
} else {
$base[$key] = $value;
}
}
}
return $base;
}
Thanks to a user on php.net. This will produce the correct output when keys are numeric.

PHP - Compare two array and remove both item in a specific index if either of the array have empty value

Refer to 2 array below:
$bar_arr =
Array
(
Array
(
[bar] => bar01.jpg
[position] => 1
)
Array
(
[bar] => bar02.jpg
[position] => 2
)
Array
(
[bar] => bar03.jpg
[position] => 3
)
)
$banner_arr =
Array
(
Array
(
[banner] =>
[position] => 1
)
Array
(
[banner] => banner02.jpg
[position] => 2
)
Array
(
[banner] => banner03.jpg
[position] => 3
)
)
$banner_arr[0][banner] don't have value, so I would like to remove this index. In the meantime$bar_arr[0][bar] would also be removed, I want to end up like this:
$bar_arr =
Array
(
Array
(
[bar] => bar02.jpg
[position] => 2
)
Array
(
[bar] => bar03.jpg
[position] => 3
)
)
$banner_arr =
Array
(
Array
(
[banner] => banner02.jpg
[position] => 2
)
Array
(
[banner] => banner03.jpg
[position] => 3
)
)
My question is how to compare this two array and remove both item in a specific index if either of the array have empty value.
Thanks
If you're just checking the value of banner and you assume that the two arrays are ordered identically, this is fairly simple (You might need to make a copy of banner_arr first ... not sure):
foreach ($banner_arr as $key => $banner) {
if (empty($banner['banner'])) {
unset($banner_arr[$key]);
unset($bar_arr[$key]);
}
}
More likely though, the order of the arrays can't be relied upon. In this case, just use an additional array of positions and track all the positions that need to be removed, and unset those:
$positions = array();
foreach ($banner_arr as $key => $banner) {
if (empty($banner['banner'])) {
$positions[] = $banner['position'];
unset($banner_arr[$key]);
}
}
then search through $bar_arr for corresponding positions:
foreach ($bar_arr as $key => $bar) {
if (in_array($bar['position'], $positions)) {
unset($bar_arr[$key]);
}
}
I'm assuming that both arrays are the same length and that the only possible missing values are in ['bar'] or ['banner'].
Basically I'd just loop through the array and store the valid values in new arrays;
$new_bar_arr = array();
$new_banner_arr = array();
$count = count($banner_arr);
$index = 0;
while($index < $count){
if(!empty($bar_arr[$index]['bar']) && !empty($banner_arr[$index]['banner'])){
$new_bar_arr[] = $bar_arr[$index];
$new_banner_arr[] = $banner_arr[$index];
}
$index++;
}
Assuming your count lines up like you've suggested:
$newArray = array_map( NULL, $banner_arr, $bar_arr );
foreach( $newArray as $key => $array ){
foreach( $array as $arr ){
if( $arr === NULL ){
unset( $newArray[$key] );
}
}
}
Even if it doesn't, I'd just make a new function and use array map still.

Group 2d array data using column value to create a 3d array

I have a multidimensional array and am trying to group them according to the value in a specific column.
I'm trying to group them by level, but I won't actually know the level beforehand. So, it's not like I can put it in a for loop and say while $i < 7, because I won't know that 7 is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did.
[
['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]
Desired result:
Array (
[1] => Array (
[0] => Array (
[cust] => XT8900
[type] => standard
)
[1] => Array (
[cust] => XT8944
[type] => standard
)
)
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
)
Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.
If not then build a temporary array to sort:
foreach ($input_arr as $key => &$entry) {
$level_arr[$entry['level']][$key] = $entry;
}
Leaves you with the form you wanted and everything referenced together.
Build the array like that in the first place though if at all possible.
You need to group them by level first
Use foreach to loop into array check if the level is the same with the previous item then group it with that array
$templevel=0;
$newkey=0;
$grouparr[$templevel]="";
foreach ($items as $key => $val) {
if ($templevel==$val['level']){
$grouparr[$templevel][$newkey]=$val;
} else {
$grouparr[$val['level']][$newkey]=$val;
}
$newkey++;
}
print($grouparr);
The output of print($grouparr); will display like the format you hoped for
You can also try to
print($grouparr[7]);
Will display
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
Or
print($grouparr[3]);
Will display
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
Here is the solution I landed on for an identical problem, wrapped as a function:
function arraySort($input,$sortkey){
foreach ($input as $key=>$val) $output[$val[$sortkey]][]=$val;
return $output;
}
To sort $myarray by the key named "level" just do this:
$myArray = arraySort($myArray,'level');
Or if you didn't want it as a function, just for a one time use, this would create $myNewArray from $myArray grouped by the key 'level'
foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val;
function group_assoc($array, $key) {
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
return $return;
}
//Group the requests by their account_id
$account_requests = group_assoc($requests, 'account_id');
$result = array();
foreach ($yourArrayList as $data) {
$id = $data['level'];
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
Best ans.
$levels = array_unique(array_column($records, 'level'));
$data = array();
foreach($records as $key => $value){
$data[$levels[array_search($value['level'],$levels )]][] = $value ;
}
print_r($data);
To generate the question's exact desured output from the sample input, pull/pop the last value from each row, use that value as the first level grouping key. Then use the original first level index as the second level key. Then push the two remaining elements into the group's subset.
Code: (Demo)
$result = [];
foreach ($array as $key => $row) {
$result[array_pop($row)][$key] = $row;
}
var_export($result);
For functional style syntax, use array_reduce(). (Demo)
var_export(
array_reduce(
array_keys($array),
function($result, $key) use ($array) {
$result[array_pop($array[$key])][$key] = $array[$key];
return $result;
}
)
);
function _group_by($array,$key,$keyName)
{
$return = array();
foreach($array as $val) {
$return[$keyName.$val[$key]][] = $val;
}
return $return;
} //end of function

Categories