-2

如何提取键以 id 结尾的元素?

我想通过键将一个数组分成两个数组,其中每个元素都有一个以它的 id 结尾的键。

数组:

array(
      'key_1' => 'some value 1',
      'key_2' => 'some value 2',
     );

现在,我有两个 ID,1 和 2。

预期的数组:

array_one(
      'id' => 1,
      'value' => 'some value 1',
     );

array_two(
      'id' => 2,
      'value' => 'some value 2',
     );

实际上,我有一个来自表单的 $_POST 数组。每个键都以其 Id 结尾,我想通过它们的 Id 将主数组分成两个数组。

这是我拥有的数组:

    Array
(
    [itemId_1] => 1
    [product_id_1] => 1
    [desc_1] => desc for the first item
    [quantity_1] => 5
    [unit_1] => kilogram
    [priceUnit_1] => 100
    [discount_1] => 0
    [taxCost_1] => 45
    [itemId_2] => 2
    [product_id_2] => 2
    [desc_2] => desc for the second item
    [quantity_2] => 10
    [unit_2] => metre
    [priceUnit_2] => 150
    [discount_2] => 0
    [taxCost_2] => 135
)

现在,我希望这些数组将它们中的每一个保存到数据库中。数组必须用 itemId 分隔:

    Array
(
    [itemId] => 1
    [product_id] => 1
    [desc] => desc for the first item
    [quantity] => 5
    [unit] => kilogram
    [priceUnit] => 100
    [discount] => 0
    [taxCost] => 45
)

    Array
(
    [itemId] => 2
    [product_id] => 2
    [desc] => desc for the second item
    [quantity] => 10
    [unit] => metre
    [priceUnit] => 150
    [discount] => 0
    [taxCost] => 135
)
4

2 回答 2

0

您可以foreach像这样编辑数组并将结果存储在新数组中。

$items = array(
    'key_1' => 'some value 1',
    'key_2' => 'some value 2',
);

$result = array(); 

foreach ($items as $index => $value){
    $id = str_replace('key_','',$index);
    $result['array_'.$id] = [
        'id' => $id,
        'value' => $value,
    ];
}

extract($result); // must return array_1 and array_2
于 2019-12-29T07:03:09.750 回答
-1

好的,我已经这样做了:

foreach ($_POST as $key => $value) {
           $array{$id[1]} = array();
           $id = explode('_', $key);
           ${"array" . $id[1]}[] = array($id[0] => $value);
        }

        $array1 = call_user_func_array('array_merge', $array1);
        var_dump($array1);

        $array2 = call_user_func_array('array_merge', $array2);
        var_dump($array2);

这会给我两个数组:

    Array
(
    [itemId] => 1
    [product_id] => 1
    [desc] => desc for the first item
    [quantity] => 5
    [unit] => kilogram
    [priceUnit] => 100
    [discount] => 0
    [taxCost] => 45
)

    Array
(
    [itemId] => 2
    [product_id] => 2
    [desc] => desc for the second item
    [quantity] => 10
    [unit] => metre
    [priceUnit] => 150
    [discount] => 0
    [taxCost] => 135
)
于 2019-12-29T08:15:50.367 回答