A
A
Alexander Semikashev2013-12-28 10:58:10
PHP
Alexander Semikashev, 2013-12-28 10:58:10

How to connect an array by key?

Hi all. Tell me please.
There is an array and there are 4 more arrays in it (this is what the database gives me).
In these arrays:

[id] => 1  [year] => 2013 [name] =>  Александр
 [id] =>2 [year] => 2013 [name] =>  Сергей
 [id] => 3 [year] => 2012 [name] =>  Никита
 [id] => 4 [year] => 2012 [name] =>  Володя

How can I combine the arrays by the year key so that it looks like this:
[yaer] => 2013 [name1] => Александр [name2] => Сергей

And also with another array.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladlen Grachev, 2013-12-28
@verng95

Do not listen to those who talk about getting data at the database level. You get a dynamic number of columns, and here you cannot do without real database programming.
In fact, the required structure is not optimal. In any case, there are no arguments in its favor so far. It is better to get something like the one below. Such data is much more convenient for further processing.

$arr = array(array('id' => 1,  'year' => 2013, 'name' =>  "Александр"),
  array('id' =>2, 'year' => 2013, 'name' =>  "Сергей"),
  array('id' => 3, 'year' => 2012, 'name' =>  "Никита"),
  array('id' => 4, 'year' => 2012, 'name' =>  "Володя"));

function by_year($arr) {
  $result = array();
  foreach ($arr as $l) {
    $result[$l['year']][] = $l['name'];
  }
  return $result;
}

print_r(by_year($arr));

Result:
Array
(
    [2013] => Array
        (
            [0] => Александр
            [1] => Сергей
        )

    [2012] => Array
        (
            [0] => Никита
            [1] => Володя
        )

)

If you need to save the user id, then put it in place of the key ( $result[$l['year']][$l['id']] = $l['name']; ).
Enter checks for NULL values ​​and others as needed, depending on the restrictions on the database tables.

_
_ _, 2013-12-28
@AMar4enko

You will have to do it either by hand or using libraries like https://github.com/Athari/YaLinqo

S
Stepan, 2013-12-28
@L3n1n

In general, this should be done at the database level. If Mysql then group by year

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question