具有多个数组的Foreach(PHP)

时间:2018-05-21 13:41:34

标签: php arrays foreach

我收到了这段代码:

$result = $phpSigep->calcPrecoPrazo($params);

foreach ($result->getResult() as $key => $shippingCorreios) {
$shipping->service = array(['name' => $shippingCorreios->get('servico')->get('nome')]);
$shipping->amount += $productsToShipping['withRules']['amount'];
dd($shipping);

$result->getResource()就像这样:

array:39 [
  0 => CalcPrecoPrazoResposta {#652
    #servico: ServicoDePostagem {#653
      #codigo: "41068"
      #idServico: 109819
      #nome: "Pac 41068"
      #_failIfAtributeNotExiste: true
    }
    #valor: 62.24
    #prazoEntrega: 7
    #valorMaoPropria: 0.0
    #valorAvisoRecebimento: 5.0
    #valorValorDeclarado: 0.57
    #entregaDomiciliar: true
    #entregaSabado: false
    #erroCodigo: 0
    #erroMsg: null
    #_failIfAtributeNotExiste: true

我需要运行foreach并返回所有数组。现在这段代码只给我最后一个数组,因为foreach在再次运行时会清理它的数据。

任何sugestions?

4 个答案:

答案 0 :(得分:0)

您在每次迭代中重新分配$shipping->service。要将新元素添加到数组,请使用[] =

foreach () {
    $shipping->service[] = array();
}

答案 1 :(得分:0)

您可以做的是将它们存储在新变量中:

$allServices = [];
$result = $phpSigep->calcPrecoPrazo($params);

foreach ($result->getResult() as $key => $shippingCorreios) {
$currentService = array(['name' => $shippingCorreios->get('servico')->get('nome')]);
$allServices[] = $currentService;
$shipping->service = $currentService;
$shipping->amount += $productsToShipping['withRules']['amount'];
dd($shipping);

然后使用$ allServices集合

简单地执行任何操作

答案 2 :(得分:0)

您正在使用以下代码创建一个新数组:

$shipping->service = array(['name' => $shippingCorreios->get('servico')->get('nome')]);

你应该像这样附加到你的数组:

$shipping->service[] = 'name' => $shippingCorreios->get('servico')->get('nome');

例如:

$array = ['banana', 'apple'];
$array = array(['coconut']);

var_dump($array); 

将返回此

array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(4) "coconut"
  }
}

答案 3 :(得分:0)

我找到了答案。

$array[$key] = [
                                'name' => $shippingCorreios->get('servico')->get('nome'),
                                'value' => $shippingCorreios->get('valor'),
                                'dead line' => $shippingCorreios->get('prazo')
                                ];