在foreach php中创建多维数组

时间:2017-12-28 20:03:51

标签: php arrays multidimensional-array foreach

我有一个foreach,它通过API检查多个请求,并仅选择那些包含前缀为sku ==“MCA”的项目的请求。但是,正如我在下面所做的那样,当我必须放置所有请求时,我只能在数组中输入一个订单。

stack exec

我期望的结果是:

foreach($listaPedidos as $pedido) :
    $i = 0;
    $somatorio = array();

    $resulta = $client->salesOrderInfo($session, $pedido->increment_id);
    foreach($resulta->items as $item) :
        $sku = $item->sku;
        if (substr($sku, 0,3) == "MCA") :
            $email = $pedido->customer_email;
            $codCli = idClienteMca($conn, $session, $client, $email);
            $dataCadastro = date("Y-m-d H:i:s");
            $qtdItens = ++$i;
            $somatorio[] = (float)$item->row_total;
            $totalPedido = array_sum($somatorio);
            $observacao = "";
            $boleto = "0";
            $transportadora = "";

            $todosPedidos = array(
                "codcli"        => $codCli,
                "datacadastro"  => $dataCadastro,
                "qtditens"      => $qtdItens,
                "totalpedido"   => $totalPedido,
                "observacao"    => $observacao,
                "boleto"        => $boleto
            );

        endif;
    endforeach;

endforeach;

如何提出所有请求,而不仅仅是最后一次迭代?

韩国社交协会!

1 个答案:

答案 0 :(得分:2)

问题 您一次又一次地在$todosPedidos内覆盖foreach()变量,这就是为什么您只得到最后一个结果。< / p>

<强> 解决方案: -

  1. 在第一个$todosPedidos = [];之前定义foreach()

  2. $todosPedidos更改为$todosPedidos[]

  3. 所以代码必须是: -

    $todosPedidos = [];
    foreach($listaPedidos as $pedido) :
        $i = 0;
        $somatorio = array();
    
        $resulta = $client->salesOrderInfo($session, $pedido->increment_id);
        foreach($resulta->items as $item) :
            $sku = $item->sku;
            if (substr($sku, 0,3) == "MCA") :
                $email = $pedido->customer_email;
                $codCli = idClienteMca($conn, $session, $client, $email);
                $dataCadastro = date("Y-m-d H:i:s");
                $qtdItens = ++$i;
                $somatorio[] = (float)$item->row_total;
                $totalPedido = array_sum($somatorio);
                $observacao = "";
                $boleto = "0";
                $transportadora = "";
    
                $todosPedidos[] = array(
                    "codcli"        => $codCli,
                    "datacadastro"  => $dataCadastro,
                    "qtditens"      => $qtdItens,
                    "totalpedido"   => $totalPedido,
                    "observacao"    => $observacao,
                    "boleto"        => $boleto
                );
    
            endif;
        endforeach;
    
    endforeach;
    print_r($todosPedidos); // to check that all data coming or not?