【问题标题】:PHP Сonvert string to nested array with keysPHPСonvert字符串到带有键的嵌套数组
【发布时间】:2023-03-15 08:00:01
【问题描述】:

我有一个字符串 - $string = '_8;1092;4,_9;1083;4,_10;1084;4,_11;1085;4;'。 我需要将它转换为这样的数组:

$args = array(
    8 => array(
        'product_id' => 1092,
        'quantity' => 4,
    ),
    9 => array(
        'product_id' => 1083,
        'quantity' => 4,
    ),
    10 => array(
        'product_id' => 1084,
        'quantity' => 4,
    ),
    11 => array(
        'product_id' => 1085,
        'quantity' => 4,
    )
);

试过这个方法:

$prods = explode( ',' , $string );
foreach ( $prods as $prod ) {
    $prodsParam = explode( ';' , $prod );
}

但这不是我所需要的。 我也不明白如何在嵌套数组的索引中转换字符串“_9”、“_10”等中的第一个值。

【问题讨论】:

    标签: php arrays string nested


    【解决方案1】:
    $string = '_8;1092;4,_9;1083;4,_10;1084;4,_11;1085;4';
    $exploded = explode(',', $string);
    $array = [];
    
    foreach ($exploded as $item) {
        $values = explode(';', $item);
        $index = (int) str_replace('_', '', $values[0]);
      
        $array[$index] = [
            'product_id' => (int) $values[1],
            'quantity' => (int) $values[2],
        ];
    }
    

    试试看。 您首先在逗号上爆炸,因为它是每个项目的分隔符。然后在 foreach 循环内爆炸“;”分隔符来获取每个值。剩下的很容易设置正确的信息(int)用于将值转换为整数值。

    输出是:

    Array
    (
        [8] => Array
            (
                [product_id] => 1092
                [quantity] => 4
            )
    
        [9] => Array
            (
                [product_id] => 1083
                [quantity] => 4
            )
    
        [10] => Array
            (
                [product_id] => 1084
                [quantity] => 4
            )
    
        [11] => Array
            (
                [product_id] => 1085
                [quantity] => 4
            )
    
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-30
      • 2018-06-25
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多