【问题标题】:Exploding a string, then inserting resulting array back into array分解一个字符串,然后将结果数组插入回数组
【发布时间】:2016-07-07 11:26:55
【问题描述】:

我有一个这样的数组:

array:3 [▼
  0 => {#472 ▼
    +"component_id": 3
    +"supplier_id": 1
    +"volumes": "100:1.5000,207:1.0100,500:0.8000,1000:0.4000"
  }
  1 => {#474 ▼
    +"component_id": 3
    +"supplier_id": 2
    +"volumes": "10000:0.2000"
  }
  2 => {#475 ▼
    +"component_id": 4
    +"supplier_id": 2
    +"volumes": "100:0.1000,500:0.0700"
  }
]

我想分解“卷”部分并从中创建自己的数组,结果如下:

[
    "component_id" => 4
    "supplier_id" => 2
    "volumes" => array:3 [▼
        100 => "0.1000",
        500 => "0.0700"
    ]
]

我已经尝试了一些东西,这是迄今为止我最接近的(注意使用 Laravel 5.2):

$components = DB::select(
                'SELECT component_id, supplier_id,
                GROUP_CONCAT(volume, \':\', unit_cost) AS volumes
                FROM component_supplier
                GROUP BY CONCAT(component_id, supplier_id)'
                );

        foreach ($components as $component) {
            $exploded = explode(",",$component->volumes);
            array_push($components, $exploded);
        }

哪个更近!但是只是将正确的格式附加到数组的末尾-我猜这是我对 array_push 的期望:)

array:6 [▼
  0 => {#472 ▼
    +"component_id": 3
    +"supplier_id": 1
    +"volumes": "100:1.5000,207:1.0100,500:0.8000,1000:0.4000"
  }
  1 => {#474 ▼
    +"component_id": 3
    +"supplier_id": 2
    +"volumes": "10000:0.2000"
  }
  2 => {#475 ▼
    +"component_id": 4
    +"supplier_id": 2
    +"volumes": "100:0.1000,500:0.0700"
  }
  3 => array:4 [▼
    0 => "100:1.5000"
    1 => "207:1.0100"
    2 => "500:0.8000"
    3 => "1000:0.4000"
  ]
  4 => array:1 [▼
    0 => "10000:0.2000"
  ]
  5 => array:2 [▼
    0 => "100:0.1000"
    1 => "500:0.0700"
  ]
]

所以我正在努力将其分解,将其转换为 key => value 格式,然后(最重要的是)将其推回数组中的正确位置。

感谢您的帮助:)

【问题讨论】:

    标签: php laravel


    【解决方案1】:
    foreach ($components as $component) {
        $volumesList = explode(',', $component->volumes);
        $volumesDictionary = [];
        foreach ($volumesList as $listItem) {
            list($key, $value) = explode(':', $listItem);
            $volumesDictionary[$key] = $value;
        }
        $component->volumes = $volumesDictionary;
    }
    

    说明: 项目用逗号分隔,键值对用冒号分隔。所以我们必须爆炸两次。将键与值分开后,我们将它们添加到字典中。最后,我们想用关联数组替换序列化字典,所以不要调用array_push(它总是将项目附加到数组的末尾,not 到最后一个项目的项目 数组中)我们只需将$component->volumes字符串替换为新创建的字典。

    【讨论】:

    • 感谢 Mad Dog 的解释和示例代码,这真的很有帮助和信息量。
    【解决方案2】:

    看起来你需要两次爆炸。像这样。

      foreach ($components as $component) {
    
            $exploded = explode(",",$component->volumes);
    
            foreach($exploded as $item)
            {
                $ex_item = explode(':', $item);
                $components[$ex_item[0]] = $ex_item[1];
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多