gpt4 book ai didi

php - 如何将字符串数组转换为 PHP 中的关联数组?

转载 作者:行者123 更新时间:2023-12-04 03:56:43 26 4
gpt4 key购买 nike

我目前有一个包含三个字符串的数组,我的目标是将数组中的这三个字符串转换为单独的关联数组。

这是数组:

$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",

我想让关联数组的键成为操作、数量、项目代码等,开始时我认为我应该尝试将数组的内容转换为字符串以使其更易于管理。

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

理想情况下,我希望数组看起来像这样。我是 PHP 的新手,因此非常感谢任何帮助和建议。

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

最佳答案

这可能是您需要的:

<?php

$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"
);



foreach ($arr as $string) {
//Build array
preg_match_all("/ [ ]?([^:]+): ([^;]+)[ ;]? /x", $string, $p);
$array = array_combine($p[1], $p[2]);

//Print it or do something else with it
print_r($array);
}

https://3v4l.org/0cnhZ

您可能还想检查一下:
PHP Split Delimited String into Key/Value Pairs (Associative Array)

关于php - 如何将字符串数组转换为 PHP 中的关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63742901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com