0

I need to flatten my subarrays of data to form a simpler / more shallow 2-dimensional array. Each row should become a flat, indexed array of unique values.

Input array:

$response = [
    695 => [
        0 => [
            '00:00',
            '01:00',
            '01:30',
            '03:30',
            '04:00',
        ]
    ],
    700 => [ 
        1 => [
            '00:00',
            '00:30',
            '01:00',
            '01:30',
            '02:00',
        ],
        2 => [
            '00:00',
            '00:30',
            '09:00',
            '06:30',
            '07:00',                    
        ]
    ]
]; 

My current code:

$result = array();
foreach ($response as $key => $list) {
  $result[$key] = array_merge($result, $list);
}
var_export($result);

but this doesn't give the proper result.

Expected output:

array (
  695 => 
  array (
    0 => '00:00',
    1 => '01:00',
    2 => '01:30',
    3 => '03:30',
    4 => '04:00',
  ),
  700 => 
  array (
    0 => '00:00',
    1 => '00:30',
    2 => '01:00',
    3 => '01:30',
    4 => '02:00',
    5 => '09:00',
    6 => '06:30',
    7 => '07:00',
  ),
)
5
  • what is expected outcome ? and also what you tried so for? Commented Jan 6, 2017 at 9:19
  • 1
    I want to merge the results based on the key - which key? What have you tried? Commented Jan 6, 2017 at 9:21
  • 1
    I give this -1 later if this post didn't explain properly about the desired output. Commented Jan 6, 2017 at 9:23
  • 1
    This is an impossible output since based on key mentioned value will be overwritten. Commented Jan 6, 2017 at 9:26
  • you will never get your desired output because same indexes values will replaced . (new-one replace old one) Commented Jan 6, 2017 at 9:29

2 Answers 2

2

merge the array like this:

$result = array_map(function($v){
  $o = [];
  foreach($v as $val)
  {
    $o = array_merge($o, $val);
  }
  return array_values(array_unique($o));
}, $array);
Sign up to request clarification or add additional context in comments.

3 Comments

check his output (it have same indexes)
how can the array have the same index
yes but i did not downvote. it still has index issue.use array_values before return.
0

The modern equivalent of @LF00's answer is as follows.

Iterate each row without affecting the first level keys. Merge (flatten) subsets of data, remove duplicates, then re-index the unique elements.

Code: (Demo)

var_export(
    array_map(
        fn($rows) =>
            array_values(
                array_unique(
                    array_merge(...$rows)
                )
            ),
        $array
    )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.