循环遍历包含数组的数组

时间:2016-04-25 10:59:15

标签: php arrays

我现在已经彻底改变了我的阵列的格式,我希望这是一个简单的误解。所以我的数组现在看起来像下面的

array:9 [▼
  0 => array:4 [▼
    "leadData" => array:7 [▼
      "LeadID" => "1232806"
      "Client" => "Some Client"
      "LeadName" => "Test"
      "Owner" => "Someone"
      "Value" => "2160.00"
    ]
    "clientData" => array:2 [▼
      "Prospect" => "No"
    ]
    "quoteData" => array:8 [▼
      "QuoteID" => "Q0020"
      "ProjectName" => "Test"
      "Amount" => "1234"
    ]
    "customData" => array:2 [▼
      0 => array:1 [▼
        "Type" => "New"
      ]
      1 => array:1 [▼
        "Month" => "June 16"
      ]
    ]
  ]
  2 => array:4 [
     ...
  ]
]

所以它现在基本上是4个内部数组。现在如果我执行以下操作,我可以打印出leadData内部数组的所有数据

foreach($leadArray as $array)
    <tr>
        foreach($array['leadData'] as $leadKey => $leadData)
            <td>
                {{ $leadData }}
            </td>
        endforeach
    </tr>
endforeach

工作正常。但是,我只想显示这个数组的某些部分。我会假设做类似以下的工作

foreach($leadArray as $array)
    <tr>
        foreach($array['leadData'] as $leadKey => $leadData)
            <td>
                {{ $leadData['LeadID'] }}
            </td>
            <td>
                {{ $leadData['LeadName'] }}
            </td>
        endforeach
    </tr>
endforeach

但是,如果我这样做,我得到非法字符串偏移错误。这不是我访问这些数据的方式吗?

P.S。忽略我做foreach循环等的方式,这是因为我使用的是模板引擎。

由于

2 个答案:

答案 0 :(得分:1)

您不必遍历第二个数组,您可以使用键来获取数据。

foreach($leadArray as $array)
    <tr>
        <td>
            {{ $array['leadData']['LeadID'] }}
        </td>
        <td>
            {{ $array['leadData']['LeadName'] }}
        </td>
    </tr>
endforeach

答案 1 :(得分:0)

Your main array will be like this, where you want to work, right?
<pre>
$aMainArray = array(
    0 => array(
        "leadData" => array(
            "LeadID" => "1232806",
            "Client" => "Some Client",
            "LeadName" => "Test",
            "Owner" => "Someone",
            "Value" => "2160.00",
        )
    )
);
foreach ($aMainArray AS $aSubArray) {
    print_r($aSubArray);
    // You can echo your required values like below
    echo $aSubArray['leadData']['LeadID'];
    echo $aSubArray['leadData']['LeadName'];
    // OR like this one
    foreach ($aSubArray AS $value) {
      echo $value['LeadID']; 
      echo $value['LeadName'];
    }
}
</pre>