C
C
CrewCut2015-12-15 15:10:05
PHP
CrewCut, 2015-12-15 15:10:05

How can you convert the value of an array element to an array?

I have an array like this:

Array
(
    ["Московская обл."] => "1 Мая","1 Поселок","2-я Смирновка","3-й Участок","4-й Участок","52127 городок",
    ["Удмуртская респ."] => "Якшур-Бодья",
)

Right now the value is a string with each element separated by a comma. How can I translate the value of each key from a string into an array, so that it turns out like this:
Array
(
    ["Московская обл."] => 
    Array (
      "1 Мая",
      "1 Поселок",
      "2-я Смирновка",
      "3-й Участок",
      "4-й Участок",
      "52127 городок"
    ),
    ["Удмуртская респ."] => 
    Array (
      "Якшур-Бодья"
    )
)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mikhail Osher, 2015-12-15
@CrewCut

$input = [
    'foo' => 'one, two, three',
    'bar' => 'baz',
];

$result = array_map(
    function ($value) {
        return array_map('trim', explode(',', $value));
    },
    $input
);

var_dump($result);

array(2) {
  ["foo"]=>
  array(3) {
    [0]=>
    string(3) "one"
    [1]=>
    string(3) "two"
    [2]=>
    string(5) "three"
  }
  ["bar"]=>
  array(1) {
    [0]=>
    string(3) "baz"
  }
}

R
romy4, 2015-12-15
@romy4

using explode

A
Andrey Mokhov, 2015-12-15
@mokhovcom

$your = [];
$ret = array_map(function ($in) {return explode(',', $in);}, $your);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question