我想迭代以下数组(这是print_r时的输出):
Array (
[GetRecentCasesResult] => Array (
[CaseHistory] => Array (
[0] => Array (
[caseNumber] => CAS-00305-Q0S7Y5
[dateCreated] => 2016-01-17 11:00:09 AM
[faultType] => Repair Blocked Sewer - Small Pipes
[status] => Open
)
[1] => Array (
[caseNumber] => CAS-00308-W4F8F0
[dateCreated] => 2016-01-17 01:17:04 PM
[faultType] => Repair Pothole in Major Road
[status] => Open
)
[2] => Array (
[caseNumber] => CAS-00309-T8B2J6
[dateCreated] => 2016-01-17 01:44:38 PM
[faultType] => Repair Pothole in Major Road
[status] => Open
)
[3] => Array (
[caseNumber] => CAS-00311-K7H8D9
[dateCreated] => 2016-01-17 02:18:29 PM
[faultType] => Electricity outage - Business
[status] => Open
)
[4] => Array (
[caseNumber] => CAS-00303-C8M0K8
[dateCreated] => 2016-01-17 10:14:45 AM
[faultType] => Electricity outage - Business
[status] => Open
)
[5] => Array (
[caseNumber] => CAS-00306-R7W8S7
[dateCreated] => 2016-01-17 11:14:40 AM
[faultType] => Animal Carcass Removal
[status] => Open
)
[6] => Array (
[caseNumber] => CAS-00307-B5Q6C0
[dateCreated] => 2016-01-17 11:17:22 AM
[faultType] => Water Leak
[status] => Open
)
)
)
)
我尝试了以下代码:
foreach ($result as $firtsone) {
foreach ($firtsone as $key => $value) {
echo $key.": ".$value;
}
}
这是我得到的错误:
注意:第30行的C:\ xampp \ htdocs \ emgtsz \ faulth.php中的数组到字符串转换 CaseHistory:数组
请协助。
答案 0 :(得分:1)
<强>问题:强>
这是我得到的结果:注意:第30行的C:\ xampp \ htdocs \ emgtsz \ faulth.php中的数组转换为字符串CaseHistory:Array
那是因为$value
并不总是一个字符串,它可能是一个数组。
解决方案:
递归迭代数组并打印(键,值)对,如下所示:
function process_array($array){
foreach($array as $key => $value){
if(is_array($value)){
process_array($value);
}else{
echo $key . ": " . $value . "<br />";
}
}
}
process_array($result);
<强>编辑:强>
我如何将这些显示为表而不是一个接一个?
使用迭代方法,如下所示:
echo "<table border='1'>";
echo "<tr>";
echo "<th>Case Number</th>";
echo "<th>Date Created</th>";
echo "<th>Fault Type</th>";
echo "<th>status</th>";
echo "</tr>";
$arrayLength = count($result['GetRecentCasesResult']['CaseHistory']);
for($i = 0; $i < $arrayLength; ++$i){
echo "<tr>";
echo "<td>" . $result['GetRecentCasesResult']['CaseHistory'][$i]['caseNumber'] . "</td>";
echo "<td>" . $result['GetRecentCasesResult']['CaseHistory'][$i]['dateCreated'] . "</td>";
echo "<td>" . $result['GetRecentCasesResult']['CaseHistory'][$i]['faultType'] . "</td>";
echo "<td>" . $result['GetRecentCasesResult']['CaseHistory'][$i]['status'] . "</td>";
echo "</tr>";
}
echo "</table>";