I have a 2D array like
attendee_programs = [1 =>[100,101],
2 =>[100,101,102]
];
I want to get array_values() and array_unique() but only for the nested elements (sorry, not sure what the terminology is) ...I.E.
programs = [100,101,102];
Is there a php function for this? or do I need to loop through and assemble it manually?
Edit: All of the answers are very helpful and have shown me something new. Sorry I can only accept one.
You could use a clever combination of array_unique, array_reduce and array_merge to achieve this:
$a = array_unique(array_reduce($attendee_programs, 'array_merge', []));
Doing this might be end in an array with some gaps in the indizes - if you need gaples array keys, you have to add array_values at the end
$a = array_values($a);
You can use:
call_user_func_array('array_merge', array_values($attendee_programs));
to get values of nested array.
array_unique(call_user_func_array('array_merge', array_values($attendee_programs)));
to get unique values.
RecursiveIteratorIterator
RecursiveArrayIterator
Solution:
function flatten($array)
{
$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
return iterator_to_array($rit, true);
}
echo '<pre>';
print_r(flatten($attendee_programs));
Result:
Array
(
[0] => 100
[1] => 101
[2] => 102
)
Yet another option:
$flat = array();
array_walk_recursive($attendee_programs, function($value) use (&$flat) {
$flat[] = $value;
});
$flat = array_unique($flat);
Related
I have a multi dimension array that I want to merge all the inside arrays into one singer dimension array, I have tried array_merge with foreach but it doesn't help.
Example Array:
$nums = array (
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
What I did but get an empty array
$newArr = [];
foreach ($nums as $value) {
array_merge($newArr, $value);
}
Expectation
$newArr = array(1,2,3,4,5,6,7,8,9)
You could use the function array_merge() this way :
$newArr = array_merge(...$nums)
It would make your code lighter and avoid the use of a foreach loop.
array_merge returns the results of the merge rather than acting on the passed argument like sort() does. You need to be doing:
$newArr = array_merge($newArr, $value);
I was wondering is it possible to convert the following array:
Array (
"2016-03-03 19:17:59",
"2016-03-03 19:20:54",
"2016-05-03 19:12:37"
)
Into this:
Array (
"2016-03-03",
"2016-03-03",
"2016-05-03"
)
Without creating any loops?
There's no explicit loops, if you can use array_map, although internally it loops:
function format_date($val) {
$v = explode(" ", $val);
return $v[0];
}
$arr = array_map("format_date", $arr);
From the PHP Manual:
array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map().
Also, when you are dealing with Dates, the right way to do is as follows:
return date("Y-m-d", strtotime($val));
The simple way, using loops is to use a foreach():
foreach($arr as $key => $date)
$arr[$key] = date("Y-m-d", strtotime($date));
This is the most simplest looping way I can think of considering the index to be anything.
Input:
<?php
$arr = array(
"2016-03-03 19:17:59",
"2016-03-03 19:20:54",
"2016-05-03 19:12:37"
);
function format_date($val) {
$v = explode(" ", $val);
return $v[0];
}
$arr = array_map("format_date", $arr);
print_r($arr);
Output
Array
(
[0] => 2016-03-03
[1] => 2016-03-03
[2] => 2016-05-03
)
Demo: http://ideone.com/r9AyYV
Yes, use map:
function first10($s) {
return substr($s, 0, 10);
}
$result = array_map("first10", $yourArray);
WARNING: this is a good solution only if you are sure that the date format does not change, in other words the first 10 characters must contain the date.
Praveen Kumar's answer is probably the better solution but there is a way to do with what wouldn't really been seen as a loop. instead you use recursion
function explodeNoLoop($array,$delim,$index=0)
{
$returnArr = array();
if(isset($array[$index]))
{
$expldoed = explode($delim,$array[$index]);
array_push($returnArr,$expldoed[0]);
}
if(isset($array[$index+1]))
{
$returnArr = array_merge($returnArr,explodeNoLoop($array,$delim,$index+1));
}
return $returnArr;
}
$myArr = array (
"2016-03-03 19:17:59",
"2016-03-03 19:20:54",
"2016-05-03 19:12:37"
);
var_dump(explodeNoLoop($myArr," "));
example
How this code works is that with the function we explode the array at the index provided by the function parameter and add this to our returning array. Then we check if there is a value set at the next index which is +1 of the index we passed into the function. If it exists then we call the function again with the new index with the same array and delimiter. We then merge the results of this with our returner array and then return that.
However, with this one should be careful of nest level errors where you excursively call a function too many times, like looking into the reflection of a mirror in a mirror.
How can I delete duplicates in array?
For example if I had the following array:
$array = array('1','1','2','3');
I want it to become
$array = array('2','3');
so I want it to delete the whole value if two of it are found
Depending on PHP version, this should work in all versions of PHP >= 4.0.6 as it doesn't require anonymous functions that require PHP >= 5.3:
function moreThanOne($val) {
return $val < 2;
}
$a1 = array('1','1','2','3');
print_r(array_keys(array_filter(array_count_values($a1), 'moreThanOne')));
DEMO (Change the PHP version in the drop-down to select the version of PHP you are using)
This works because:
array_count_values will go through the array and create an index for each value and increment it each time it encounters it again.
array_filter will take the created array and pass it through the moreThanOne function defined earlier, if it returns false, the key/value pair will be removed.
array_keys will discard the value portion of the array creating an array with the values being the keys that were defined. This final step gives you a result that removes all values that existed more than once within the original array.
You can filter them out using array_count_values():
$array = array('1','1','2','3');
$res = array_keys(array_filter(array_count_values($array), function($freq) {
return $freq == 1;
}));
The function returns an array comprising the original values and their respective frequencies; you then pick only the single frequencies. The end result is obtained by retrieving the keys.
Demo
Try this code,
<?php
$array = array('1','1','2','3');
foreach($array as $data){
$key= array_keys($array,$data);
if(count($key)>1){
foreach($key as $key2 => $data2){
unset($array[$key2]);
}
}
}
$array=array_values($array);
print_r($array);
?>
Output
Array ( [0] => 2 [1] => 3 )
PHP offers so many array functions, you just have to combine them:
$arr = array_keys(array_filter(array_count_values($arr), function($val) {
return $val === 1;
}));
Reference: array_keys, array_filter, array_count_values
DEMO
Remove duplicate values from an array.
array_unique($array)
$array = array(4, "4", "3", 4, 3, "3");
$result = array_unique($array);
print_r($result);
/*
Array
(
[0] => 4
[2] => 3
)
*/
I have two arrays like this
$arr1 = Array('fn', 'ln', 'em');
$arr2 = Array('fn'=>'xyz', 'ano' => 'abc', 'ln'=>'122', 'em' => 'a#b.com', 'db'=>'xy');
I want to create an array from arr2 with all the elements from $arr1. So the result should be like this.
$result = Array( 'fn'=>'xyz', 'ln'=>'122', 'em'='a#b.com');
Don't want to loop.
Any idea?
The order of arguments is important here
print_r(array_intersect_key($arr2, array_flip($arr1)));
You can use array_map for this.
// PHP 5.3+ only
$result = array_combine($arr1, array_map(function($a) use($arr2){
return $arr2[$a];
}, $arr1));
DEMO: http://codepad.viper-7.com/Y1aYcf
If you have PHP < 5.3, you can do some trickery with array_intersect_key and array_flip.
$result = array_intersect_key($arr2, array_flip($arr1));
DEMO: http://codepad.org/MuydURQT
You just have to loop, as in create a new array or maybe check some array set in mathematics functions. I think, maybe, insection might work.
I don't want to use array_merge() as it results in i misunderstood that all values with the same keys would be overwritten. i have two arrays
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
and would like to combine them resulting like this
array(0=>'foo', 1=>'bar',2=>'bar', 3=>'foo');
array_merge() appends the values of the second array to the first. It does not overwrite keys.
Your example, results in:
Array (
[0] => foo
[1] => bar
[2] => bar
[3] => foo )
However, If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Unless this was just an example to another problem you were having?
Does this answer your question? I'm not sure exactly what you're trying to accomplish, but from your description it sounds like this will work:
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
foreach ($array2 as $i) {
$array1[] = $i;
}
echo var_dump($array1);
If someone stumbles upon this, this is a way to do it nowadays:
var_dump(array_merge_recursive($array1, $array2));
There are probably much better ways but what about:
$newarray= array();
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
$dataarrays = array($array1, $array2);
foreach($dataarrays as $dataarray) {
foreach($dataarray as $data) {
$newarray[] = $data;
}
}
print_r($newarray);
$result = array_keys(array_merge(array_flip($array1), array_flip($array2)));
var_dump($result);