P
P
Pavel Ivanov2014-09-26 17:06:39
PHP
Pavel Ivanov, 2014-09-26 17:06:39

How to quickly split an array in php?

In general, the question is not tied to php, but to the algorithm in general, but the task is to solve this problem with as few lines of code as possible and beautifully.
There is an associative array obtained by querying the database.
Those.
| id | activities | work |
|-----|----------|-----------------|
| 1 | a | do something |
| 1 | b | read something |
| 2 | a | write something |
| 2 | b | blablabla |
| 2 | c | do something |
| 3 | a | read something |
| 3 | b | write something |
| 3 | c | blablabla |
I would like to get an associative array like this:
(1) => ((a, do something), (b, read something))
(2) => ((a, write something), (b, blablabla), (c, do something))
and so
on It can be done?
And what if the left side is not just 1 or 2, but (1, type) or (1, type, stage)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-09-26
Protko @Fesor

array_reduce

$result = array_reduce($rows, function ($result, $row) {
    $id = array_shift($row);
     if(!isset($result[$id])) $result[$id] = [];
     $result[$id][] = $row;

     return $result;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question