How to remove duplicate values from array - php - php

I am trying to remove duplicate and empty values from array with array_unique() function, but getting wrong output.
Data:
Array (
[0] => Array (
[0] =>
[1] => 1
[2] =>
[3] => 108
[4] =>
)
[1] => Array (
[0] =>
[1] => 1
[2] =>
[3] => 108
[4] =>
[5] => 101
)
[2] => Array (
[0] =>
[1] =>
[2] => 108
[3] =>
)
)
PHP:
$array = array_filter($userids);
$arrays = array_unique($array, SORT_REGULAR);
print_r($arrays);
nothing happens with SORT_REGULAR - output comes same as raw data, and without SORT_REGULAR this output is coming:
$array = array_filter($userids);
$arrays = array_unique($array);
print_r($arrays);
output:
Array (
[0] => Array
(
[0] =>
[1] => 1
[2] =>
[3] => 108
[4] =>
)
)
output I am looking for:
Array (
[0] => Array
(
[0] => 1
[1] => 108
[2] => 101
)
)

Those array functions only works on a single level. If you flatten the array (adding all elements in a single element array), it should be pretty straight forward.
Flatten the array
$array = array_merge(...$array);
Note: This method works fine for flattening indexed arrays like in your example, but not for associative arrays where any of the sub arrays contains the same keys.
Then filter out all empty
$array = array_filter($array);
and then remove all duplicates
$array = array_unique($array);
Or as a one-liner:
$array = array_unique(array_filter(array_merge(...$array)));
Demo: https://3v4l.org/pEJAJ

Related

How to split string into an associative array which has arrays within arrays

I have the following string: names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400
I was wondering if there is a function which can split this into an associative array which as arrays within it. For example
Array (
["name"] => Array
(
bob,
mike,
sam
)
["age"] => Array
(
30,
23,
22
)
["fav-nums"] => Array
(
200,
300,
400
)
)
You can user parse_str() and explode() functions to achieve this.
Steps:
1) Use parse_str() function, it will split your string into associative array.
2) Now loop over it and go for key values.
3) keys will be the required keys (names, age and fav-nums) and you want values to be array.
4) explode() the values with ; and you will get required values.
Working code:
$str = "names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400";
parse_str($str, $output);
$arr = [];
if (! empty($output)) {
foreach ($output as $key => $value) {
$arr[$key] = explode(';', $value);
}
}
echo '<pre>';print_r($arr);echo '</pre>';
Output:
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)
Not sure if there is a direct method of creating the sub-arrays, but parse_str() will split the initial string by & and create the starting point, then process each element with explode() (and array_walk()) to create the sub-arrays.
$start = 'names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400';
parse_str($start, $output);
array_walk($output, function ( &$data ) { $data = explode(";", $data); });
print_r($output);
which gives...
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)
You can use array_map function in order to traverse the whole array as it boost up speed of your code. Also parse_str is always use in order to read Query String and convert it in array form.
$text = 'names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400';
parse_str($text, $outputArray);
$array = [];
if(!empty($outputArray)) {
$array = array_map(
function($v) {
return explode(';', $v);
}, $outputArray
);
}
echo"<pre>";
print_r($array);
The result shows
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)

Remove key from mixed array and reindex

I am new to postgresql with php. I get below array using pg_fetch_array() function.
Array
(
[0] =>
[name] =>
[1] => 1
[status] => 1
[2] => C2005
[code] => C2005
)
after removing index 1 and value of key status, i have to reindex this array so that expected output should become like:
Array
(
[0] =>
[name] =>
[1] => C2005
[code] => C2005
)
I tried
unset($row[1]);
unset($row['status'];
$foo = array_values($row);
echo "<pre>";
print_r($foo)
echo "</pre>";
and got output
Array
(
[0] =>
[name] =>
[2] => C2005
[code] => C2005
)
How the numeric index can be re-indexed after removing particular keys from the array?
You can filter the array by their key. Live demo.
unset($array['status']);
$number_keys = array_values(array_filter($array, function($k){return is_int($k) && $k != 1;}, ARRAY_FILTER_USE_KEY));
$nonnumber_keys = array_filter($array, function($k){return is_string($k);}, ARRAY_FILTER_USE_KEY);
$result = array_merge($number_keys, $nonnumber_keys);

single indexed multiple arrays to one array

I have a number of arrays:
Array ( [0] => A-I-only )
Array ( [0] => B-III-only )
Array ( [0] => C-I-and-II-only )
Array ( [0] => D-II-and-III-only )
Array ( [0] => E-I,-II,-III )
I want to put each array's first row in one array, like this:
Array( [0] => A-I-only [1] =>B-III-only [2] => C-I-and-II-only [3] => D-II-and-III-only [4] => E-I,-II,-III )
Is there a way to do it?
Use can use array merge function. Like:
$array = array_merge($array1,$array2,...);
Please note though that this would not work properly if your common indices were of string type (there would be a value overriding). Take a look here for more.
$array0 = array('A-I-only');
$array1 = array('B-III-only');
$array2 = array('C-I-and-II-only');
$array3 = array('D-II-and-III-only');
$array4 = array('E-I,-II,-III');
$result = array_merge($array0, $array1, $array2, $array3,
$array4);
print_r($result);
The Above code will give result as below
Array
(
[0] => A-I-only
[1] => B-III-only
[2] => C-I-and-II-only
[3] => D-II-and-III-only
[4] => E-I,-II,-III
)

Sort Multi Dimensional Array by its keys from another arrays values

This is an issue I haven't come across before, and there doesn't appear to be a function for this.
I'm trying to sort the following multi dimensional array by its keys
Array (
[hiphop] => Array (
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
[rnb] => Array (
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
[dubstep] => Array ( )
[reggae] => Array ( )
[trap] => Array ( )
)
From this arrays values
Array (
[0] => hiphop
[1] => dubstep
[2] => reggae
[3] => trap
[4] => rnb
[5] => rnb
)
Has anyone attempted this before or know a workaround?
An explanation would be great as I'm new to multi dimensional arrays
Many thanks in advance if you can help!
The final output would match the value organsiation from the non multi dimensional array like so
Array (
[hiphop] => Array (
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
[dubstep] => Array ( )
[reggae] => Array ( )
[trap] => Array ( )
[rnb] => Array (
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
)
The easiest Way would be to "flip" the array definining the sorting - then grab the values matching the new keys in the other array:
$s = array ("hiphop","dubstep","reggae","trap","rnb");
$target = array_flip($s);
foreach($target AS $key => &$value){
$value = $array_containing_unsorted_values[$key];
}
Note: does not work if the same value appears twice in the sorting array - but that never should happen, cause does not make sence for a sorting-definition.
Should be way faster than using array_search 2 times within each sorting comparission.
result:
Array
(
[hiphop] => Array
(
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
[dubstep] => Array
(
)
[reggae] => Array
(
)
[trap] => Array
(
)
[rnb] => Array
(
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
)
You can use uksort for that, which lets you sort by key, based on a user supplied comparison function. Using that function, you can make a function yourself, so you can hide the complex functionality in an easy one.
For instance, you want a function like ksort, only you want to specify an external array of keys, so such a function could look like this:
bool ksort_ext(&$array, $keys)
For the implementation, you can wrap uksort, like so:
function ksort_ext(&$array, $keys)
{
return uksort($array, function($a, $b) use ($keys) {
// Result of callback is based on the position of $a and $b in $keys
return array_search($a, $keys) - array_search($b, $keys);
});
}
Then, you can call it like you would call other sort functions, only with the external array of keys as a second parameter.
$array1 = array(
'hiphop' => array(1,2,3),
'rnb' => array(1,2,3),
'dubstep' => array(1,2,3),
'reggae' => array(1,2,3),
'trap' => array(1,2,3));
$array2 = array('hiphop', 'dubstep', 'reggae', 'trap', 'rnb');
var_dump(ksort_ext($array1, $array2)); // Should return true
var_dump($array1); // Should display the ordered array,

How to unset last item in multidimensional array?

I have a array like below
Array
(
[0] => Array
(
[0] => Date
[1] => Name
[2] => Hours
)
[1] => Array
(
[0] => 2013-01-02
[1] => Test User
[2] => 7:59
)
[2] => Array
(
[0] => 2013-01-03
[1] => Test User
[2] => 7:53
)
[3] => Array
(
[0] => 2013-01-04
[1] => Test User
[2] => 8:12
)
.
.
.
.
[16] => Array
(
[0] =>
[1] => Total
[2] => 103:1
)
[17] => Array
(
[0] =>
)
)
And want to remove last item from array, I have tried array_pop but this is not working after passing above array to array_pop gives me output
Array
(
[0] =>
)
How can I achieve this with minimum code.
Try:
unset ($array_name[count($array_name)-1]);
$callback = function(&$array) { array_pop($array); };
array_walk($array, $callback);
This will pop the last element from each triplet.
Try like
$my_cnt = count($my_arr);
unset($my_arr[$my_cnt-1]);
if all your arrays are indexed by numbers from zero to max without any breaks, you can use
unset($ar[count($ar)-1]);
otherwise try
end($ar);
unset($ar[key($ar)]);
You are seeing the "popped" element instead of the modified array.
array_pop() returns the data in the element that it removes from the array.
This means that you wrote:
print_r(array_pop($array));
Instead, modify the array with array_pop(), then print the array.
array_pop($array);
print_r($array);

Categories