如何在PHP中将字符串数组转换为关联数组? [英] How can I convert an array of strings into an associative array in PHP?

查看:83
本文介绍了如何在PHP中将字符串数组转换为关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个由三个字符串组成的数组,我的目标是将这三个字符串从该数组转换为单独的关联数组。

I currently have an array of three strings, and my goal is to turn these three strings from the array into individual associative arrays.

这是数组:

$arr = array(

  "action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",

  "action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",

  "action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",

我想让关联数组的键为操作,数量,项目代码等,并且首先,我想我应该尝试将数组的内容转换为

I'd like to have the key of the associative array be the action, quantity, item code etc and to start off I thought I should try turning the contents of the array into a string to make it more manageable.

// Convert $arr to a string.
$imploded = implode(": ",$arr);
//echo $imploaded;
$str = $imploded;
$results = preg_split('/: [;,]/', $str);
print_r($results);

理想情况下,我希望数组看起来像这样。我对PHP还是很陌生,所以任何帮助和建议都将不胜感激。

Ideally, i'd like the array to look like this. I'm quite new to PHP so any help and advice would be much appreciated.

array(
    'action'    =>   '',
    'amount'    =>   '',
    'code'  =>   '',
    'name'  =>   '',
    'colour'    =>   '',
    'size'      =>   '',
);


推荐答案

很简单:

$arr = array(
    "action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
    "action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
    "action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",
);
  
$data = [];
foreach ($arr as $line) {
    $newItem = [];
    foreach (explode(';', $line) as $item) {
        $parts = explode(':', $item);
        $newItem[trim($parts[0])] = trim($parts[1]);
    }
    $data[] = $newItem;
}

print_r($data);

小提琴此处

这篇关于如何在PHP中将字符串数组转换为关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆