Question

I've an array in php something like below

Array
(
    [0] => Array
        (
            [0] => 40173
            [1] => 514081
            [2] => 363885
            [3] => 891382
        ),
    [1] => Array
        (
            [0] => 40173
            [1] => 5181
            [2] => 385
            [3] => 891382
        )

)

Now I want to remove the parents indexes 0,1... and finally want to get all the values (only unique values).

Thanks.

Was it helpful?

Solution

One possible approach is using call_user_func_array('array_merge', $arr) idiom to flatten an array, then extracting unique values with array_unique():

$new_arr = array_unique(
  call_user_func_array('array_merge', $old_arr));

Demo. Obviously, it'll work with array of any length.

OTHER TIPS

$startArray = Array
(
[0] => Array
    (
        [0] => 40173
        [1] => 514081
        [2] => 363885
        [3] => 891382
    ),
[1] => Array
    (
        [0] => 40173
        [1] => 5181
        [2] => 385
        [3] => 891382
    )

);
//Edited to handle more the 2 subarrays
$finalArray = array();

foreach($startArray as $tmpArray){
    $finalArray = array_merge($finalArray, $tmpArray);
}

$finalArray = array_unique($finalArray);

Using RecursiveArrayIterator Class

$objarr = new RecursiveIteratorIterator(new RecursiveArrayIterator($yourarray));
foreach($objarr as $v) {
    $new_arr[]=$v;
}
print_r(array_unique($new_arr));

Demo

OUTPUT:

Array
(
    [0] => 40173
    [1] => 514081
    [2] => 363885
    [3] => 891382
    [5] => 5181
    [6] => 385
)
$new_array = array_merge($array1, $array2);
$show_unique = array_unique($new_array);
print_r($show_unique);

array_merge is merging the array's, array_unique is removinge any duplicate values.

Try something like this:

$new_array = array();

foreach($big_array as $sub_array) {
    array_merge($new_array, $sub_array);
}

$new_array = array_unique($new_array);

(code not tested, this just a concept)

Try this:

$Arr = array(array(40173, 514081, 363885, 891382),
             array(40173,5181, 385,891382));

$newArr = array();

foreach($Arr as $val1)
{

foreach($val1 as $val2)
{  
     array_push($newArr, $val2);
}
}

echo '<pre>';
print_r(array_unique($newArr));

Output:

Array
(
    [0] => 40173
    [1] => 514081
    [2] => 363885
    [3] => 891382
    [5] => 5181
    [6] => 385
)

Refer: https://eval.in/124240

-- Thanks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top