0

I have this multidimentional array in PHP

Array (
[4570] => Array
    (
        [id] => 1647
        [date] => 2017-13
    )

[4571] => Array
    (
        [id] => 1647
        [date] => 2017-14
    )

[4573] => Array
    (
        [id] => 1705
        [date] => 2017-15
    )

[4574] => Array
    (
        [id] => 1705
        [date] => 2017-15
    )
 )

I want to make an array like this:

Array
(
  [2017-13] => Array
  (
     all the ids associated with 2017-13
  )

  [2017-14] => Array
  (
     all the ids associated with 2017-14
     [id]
     [id]
     ...
  )
)

etc

1
  • Please try at least something Commented Apr 14, 2017 at 9:42

3 Answers 3

1

This probably is what you are looking for:

<?php
$input = [
    4570 => [
        'id' => 1647,
        'date' => '2017-13'
    ],
    4571 => [
        'id' => 1647,
        'date' => '2017-14'
    ],
    4573 => [
        'id' => 1705,
        'date' => '2017-15'
    ],
    4574 => [
        'id' => 1705,
        'date' => '2017-15'
    ]
];
$output = [];

array_walk($input, function($entry) use (&$output) {
    $output[$entry['date']][] = $entry['id'];
});

print_r($output);

The output of above code obviously is:

Array
(
    [2017-13] => Array
        (
            [0] => 1647
        )

    [2017-14] => Array
        (
            [0] => 1647
        )

    [2017-15] => Array
        (
            [0] => 1705
            [1] => 1705
        )

)

If you want to prevent ids getting added twice (as in the example for key 2017-15), you simply add a condition:

array_walk($input, function($entry) use (&$output) {
    if (   ! isset($output[$entry['date']]) 
        || ! in_array($entry['id'], $output[$entry['date']])) {
        $output[$entry['date']][] = $entry['id'];
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Thats not an sort. I would solve this by creating a new array by iterating over your current one.

$t = [];
foreach ($array as $item) {
    if (!isset($t[$item['date']]) {
        $t[$item['date']] = [];
    }
    $t[$item['date']][] = $item['id'];
}

1 Comment

if (!isset($t[$item['date']]) { $t[$item['date']] = []; } can be completely omitted. When pushing child elements with square brace syntax, the parent element(s) need not be instantiated.
0

You could try something like this:

<?php

$sourceArray = array(
    array(
        'id' => 1647,
        'date' => '2017-13'
    ),
    array(
        'id' => 1647,
        'date' => '2017-13'
    ),
    array(
        'id' => 1647,
        'date' => '2017-14'
    )
);

$resultArray = array();

foreach ($sourceArray as $k=>$v) {
    $resultArray[$v['date']][] = $v['id'];
}

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.