E
E
exedis2017-07-11 13:20:31
PHP
exedis, 2017-07-11 13:20:31

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

1 answer(s)
A
Alexander Pushkarev, 2017-07-11
@AXP-dev

Do not use such keys. Bring the array to the form

$data = [
    [
        'name' => 'Москва и Московская обл.',
        'items' => ['Москва', 'Абрамцево']
    ],
    [
        'name' => 'Санкт-Петербург',
        'items' => ['Санкт-Петербург', 'Александровская']
    ]
];

I do not pretend to gugu php, but here:
spoiler
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 question

Ask a Question

731 491 924 answers to any question