Answer the question
In order to leave comments, you need to log in
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] => Володя
[yaer] => 2013 [name1] => Александр [name2] => Сергей
Answer the question
In order to leave comments, you need to log in
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));
Array
(
[2013] => Array
(
[0] => Александр
[1] => Сергей
)
[2012] => Array
(
[0] => Никита
[1] => Володя
)
)
You will have to do it either by hand or using libraries like https://github.com/Athari/YaLinqo
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question