php按键在多维数组中组合数组

时间:2021-08-16 21:31:35

I have the following array from $_POST:

我有$ _POST的以下数组:

array { 
["item"]=> array() { 
    [0]=> "pen" 
    [1]=> "pencil" 
    [2]=> "ruler" 

array { 
["note"]=> array() { 
    [0]=> "permanent" 
    [1]=> "not so permanent" 
    [2]=> "measures stuff" 

array { 
["cost"]=> array() { 
    [0]=> "67.99" 
    [1]=> ".15" 
    [2]=> "1.49"

That I want to combine into single line items, e.g

我希望将它组合成单行项目,例如

array { 
["line_items"]=> array() {

["0"]=> array() {
        [item]=> "pen" 
        [note]=> "permanent"
        [cost]=> "67.99"

["1"]=> array() {
        [item]=> "pencil" 
        [note]=> "not so permanent"
        [cost]=> ".15"      

["3"]=> array() {
        [item]=> "ruler" 
        [note]=> "measures stuff"
        [cost]=> "1.49" 

I've had a look at array_merge, array_merge_recursive, array_combine, but all these functions don't do what i'm looking for. I've tried a few different for each and for loops, but I just can't get my head around it.

我已经看过array_merge,array_merge_recursive,array_combine,但所有这些函数都没有做我正在寻找的东西。我已经为每个和循环尝试了一些不同的东西,但我无法理解它。

Please ask if you need more info, this isn't very clear, but like i say, my head - struggling to get around this.

请问你是否需要更多信息,这不是很清楚,但就像我说的那样,我的头脑 - 努力解决这个问题。

1 个解决方案

#1


2  

You'll have to come up with something on your own for this:

你必须自己想出一些东西:

$length = count($_POST['item']);
$items = array();
for ($i = 0; $i < $length; $i++) {
    $item = array();
    $item['item'] = $_POST['item'][$i];
    $item['note'] = $_POST['note'][$i];
    $item['cost'] = $_POST['cost'][$i];
    $items[] = $item;
}

var_dump($items);

Should get you what you need. Note that it has no error checking or validation of any kind - you'll want to add that.

应该得到你需要的东西。请注意,它没有任何错误检查或验证 - 您需要添加它。

Edit: made a stupid mistake in my answer - corrected.

编辑:在我的回答中犯了一个愚蠢的错误 - 纠正了。

#1


2  

You'll have to come up with something on your own for this:

你必须自己想出一些东西:

$length = count($_POST['item']);
$items = array();
for ($i = 0; $i < $length; $i++) {
    $item = array();
    $item['item'] = $_POST['item'][$i];
    $item['note'] = $_POST['note'][$i];
    $item['cost'] = $_POST['cost'][$i];
    $items[] = $item;
}

var_dump($items);

Should get you what you need. Note that it has no error checking or validation of any kind - you'll want to add that.

应该得到你需要的东西。请注意,它没有任何错误检查或验证 - 您需要添加它。

Edit: made a stupid mistake in my answer - corrected.

编辑:在我的回答中犯了一个愚蠢的错误 - 纠正了。