Answer the question
In order to leave comments, you need to log in
How to fill such an array in a loop?
Hello, I need to fill an array of this kind in a loop. What is the best way to do this?
$city= array (
'Москва и Московская обл.' => array (0 => 'Москва', 1 => 'Абрамцево'),
'Санкт-Петербург' => array (0 => 'Санкт-Петербург', 1 => 'Александровская'),
);
Answer the question
In order to leave comments, you need to log in
Do not use such keys. Bring the array to the form
$data = [
[
'name' => 'Москва и Московская обл.',
'items' => ['Москва', 'Абрамцево']
],
[
'name' => 'Санкт-Петербург',
'items' => ['Санкт-Петербург', 'Александровская']
]
];
class Location
{
private $data;
/**
* Location constructor.
*
* @param array $data
*/
function __construct($data = [])
{
$this->data = $data;
}
/**
* Get cities by region
*
* @param string $region
*
* @return array
*/
public function getCitiesByRegion($region)
{
$key = array_search($region, array_column($this->data, 'region'));
if ( $key === false ) return false;
return $this->data[$key]['items'];
}
}
$data = [
[
'region' => 'Москва и Московская обл.',
'items' => ['Москва', 'Абрамцево']
],
[
'region' => 'Санкт-Петербург',
'items' => ['Санкт-Петербург', 'Александровская']
]
];
$location = new Location($data);
print_r($location->getCitiesByRegion('Санкт-Петербург'));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question