PHP中的多维数组和爆炸功能

时间:2019-05-10 14:35:34

标签: php arrays multidimensional-array explode

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

所需的输出:

[
    {
        "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);

}

5 个答案:

答案 0 :(得分:1)

您只需要在两个不同的变量中获取这些值,然后将其分配给新变量,例如$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 —返回值的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

答案 1 :(得分:1)

您当前正确地遍历了对象,但是您需要以正确的方式构建数组,其中包含键名:

$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

答案 2 :(得分:1)

一种选择是使用array_map遍历爆炸字符串。使用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"
}]

答案 3 :(得分:1)

$keyquickSwap答案中不是必需的:

    $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
       ];
    }

答案 4 :(得分:1)

您可以将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