根据PHP中的字符串内容创建数组

时间:2018-07-13 08:03:08

标签: php

我有一个包含多个键值的字符串,我想获取这些值并从中创建一个数组。

将以相同方式构建字符串,但可能包含更多键或更少键。字符串的一个例子是

"title:'this is the new title', msg:'this_is_updated', body:'this is the new body text'

所以我需要某种方法将这些键从字符串转换为如下所示的数组

$array['customMessage'] = [
  'title' => 'this is the new title',
  'msg' => 'this_is_updated',
  'body' => 'this is the new body'
];

5 个答案:

答案 0 :(得分:2)

如果始终采用这种格式

home

如您所示,然后使用爆炸

key: val, key:val

答案 1 :(得分:1)

首先,您应该始终尝试使用已经存在的格式。举例来说,JSON是完美的选择,而PHP已经具有与之兼容的功能。

如果由于某种原因这是不可能的,则可以使用以下命令获得结果字符串:

$string = "title:'this is the new title', msg:'this_is_updated', body:'this is the new body text'";

$firstExplode = explode(',', $string);

foreach($firstExplode as $explode) {
  $val = explode(':', $explode);
  $arr[$val[0]] = $val[1];
}

var_dump($arr);

输出:

array(3) {
  ["title"]=>
  string(23) "'this is the new title'"
  [" msg"]=>
  string(17) "'this_is_updated'"
  [" body"]=>
  string(27) "'this is the new body text'"
}

答案 2 :(得分:0)

这是逻辑

$str = "title:'this is the new title', msg:'this_is_updated', body:'this is the new body text' ";
        $str1 = explode(',', $str);
        $array['customMessage'] = array();
        foreach ($str1 as $key => $value) {
            $str2 = explode(':', $value);

            $array['customMessage'][$str2[0]] = $str2[1];
        }


        print_r($array['customMessage']);die;

答案 3 :(得分:0)

如果可能,您可以以JSON格式构建字符串,并使用json_decode()如下:

$json = '{
    "title":"this is the new title",
    "msg":"this_is_updated",
    "body":"this is the new body text"
}';

$array = json_decode($json, true);

$arrayFinal = array();
$arrayFinal['customMessage'] = $array;

echo '<pre>';
print_r($arrayFinal);
echo '</pre>';

这将给出以下输出:

Array
(
    [customMessage] => Array
        (
            [title] => this is the new title
            [msg] => this_is_updated
            [body] => this is the new body text
        )

)

答案 4 :(得分:0)

字符串是一个简单的JSON对象,只需使用此本机函数进行解码

$array = json_decode($string)