Line and colon separated list to array PHP

我们两清 提交于 2019-12-12 02:55:15

问题


I'm trying to work out a simple way to take a list, like this

foo: Alpha
bar: Bravo
fooBar: Charlie

And turn this into an associative array so that values would be

$array['foo'] //would contain Alpha
$array['bar'] //would contain Bravo

etc.

What is the cleanest way to achieve this ?


回答1:


Something like this?:

$string = "foo: Alpha
bar: Bravo
fooBar: Charlie";

$array = array();
$lines = explode("\n", $string);

foreach ($lines as $line) {
    list($key, $value) = explode(": ", $line);
    $array[$key] = $value;
}

var_dump($array);


Result:

array(3) {
  ["foo"]=>
  string(6) "Alpha
"
  ["bar"]=>
  string(6) "Bravo
"
  ["fooBar"]=>
  string(7) "Charlie"
}



回答2:


You can do it manually if your first list is already in an array:

$array = [];
$list = ['foo: Alpha', 'bar: Bravo'];

foreach ($list as $element) {
    $parts = explode(': ', $element);
    $array[$parts[0]] = $parts[1];
}

Otherwise, simply use parse_ini_string to parse a string that contains your data into an associative array (note that this function requires PHP 5.3 or greater).

If your data is in a string, and you don't have PHP 5.3, you can split on new lines to get an array: $list = explode("\n", $string);.




回答3:


Try this : $array = array();

$str    = 'foo: Alpha';
$res    = explode(":",$str);
$array[$res[0]] = $res[0];



回答4:


Maybe this is overkill but if your file format is likely to expand, it's worth looking into YAML, your example happens to be valid YAML markup. So you could for example use the Symfony YAML component

use Symfony\Component\Yaml\Yaml;
$array = Yaml::parse('/path/to/file.yml');

It works with your current format and if you decide to add nested arrays or other non-trivial data, just use the YAML syntax, which is quite intuitive. Here is an introduction to the format: http://symfony.com/doc/2.0/components/yaml/yaml_format.html



来源:https://stackoverflow.com/questions/15086520/line-and-colon-separated-list-to-array-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!