PHP 中的多维数组和爆炸函数

Multi-dimensional array and explode function in PHP

我很难获得关于多维数组的所需输出,请帮助我,谢谢

期望的输出:

[
    {
        "sku" : "11111",
        "qty" : "1"
    },
    {
        "sku" : "22222",
        "qty" : "1"
    },
    {
        "sku" : "33333",
        "qty" : "1"
    },
    {
        "sku" : "44444",
        "qty" : "1"
    }
]

我的代码:

$string = "11111*1; 22222*1; 33333*1; 44444*1";

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

foreach($array as $k=>$v){

  $array[$k] = explode('*', $v);

}

你只需要在两个不同的变量中获取这些值,然后将其分配给新变量,比如 $result

$string = "11111*1; 22222*1; 33333*1; 44444*1";
$array  = explode('; ', $string);
foreach ($array as $k => $v) {
    list($sku, $qty)   = explode('*', $v);
    $result[$k]['sku'] = $sku;
    $result[$k]['qty'] = $qty;
}
echo json_encode($result);

json_encode — Returns 值的 JSON 表示
list — 像分配数组一样分配变量

输出

[{
    "sku": "11111",
    "qty": "1"
}, {
    "sku": "22222",
    "qty": "1"
}, {
    "sku": "33333",
    "qty": "1"
}, {
    "sku": "44444",
    "qty": "1"
}]

Demo.

编辑

您可以使用 array_combine 来实现同样的效果。

foreach ($array as $k => $v) {
    $result[$k]   = array_combine(['sku', "qty"],explode('*', $v));
}

Demo

您目前正在正确地遍历对象,但您需要以正确的方式构建包含键名的数组:

$string = "11111*1; 22222*1; 33333*1; 44444*1";
$array  = explode('; ', $string);
$new    = [];

foreach($array as $k => $v){
    $parts = explode('*', $v);

    $new[] = [
        'sku' => $parts[0],
        'qty' => $parts[1],
    ];
}

Here's a demo

一种选择是使用 array_map to loop thru the exploded string. Use json_encode 将数组转换为 json

$string = "11111*1; 22222*1; 33333*1; 44444*1";

$result = array_map(function($v){
    $t =  explode("*", $v);
    return array( "sku" => trim( $t[0] ), "qty" => trim( $t[1] ));      
}, explode(";", $string));

echo json_encode( $result );

这将导致:

[{
  "sku": "11111",
  "qty": "1"
}, {
  "sku": "22222",
  "qty": "1"
}, {
  "sku": "33333",
  "qty": "1"
}, {
  "sku": "44444",
  "qty": "1"
}]

$key 不需要 答案:

    $string = "11111*1; 22222*1; 33333*1; 44444*1";
    $array  = explode('; ', $string);
    foreach ($array as $value) {
        list($sku, $qty) = explode('*', $value);
        $result[] = [
            'sku' => $sku,
            'qty' => $qty
       ];
    }

您可以将 array_walkexplodejson_encode 与参数 JSON_PRETTY_PRINT

一起使用
$string = "11111*1; 22222*1; 33333*1; 44444*1";
$strToArray = explode(';',$string);
$res=[];
array_walk($strToArray, function($v, $k) use (&$res){
  $res[$k] = [
    'sku' => substr($v, 0, strpos($v, '*')),
    'qty' => substr($v,strpos($v, '*')+1, strlen($v))
  ];
});
echo json_encode($res,JSON_PRETTY_PRINT);

Live Demo