我有一个这样的数组:
$tset = "MAIN_TEST_SET";
$gettc = "101";
$getbid = "b12";
$getresultsid = "4587879";
$users["$tset"] = array(
"testcase"=>"$gettc",
"buildid"=>"$getbid",
"resultsid"=>"$getresultsid"
);
PHP中的数组令我感到困惑。
我希望显示如下:
MAIN_TEST_SET
101 b12 4587879
102 b13 4546464
103 b14 5545465
MAIN_TEST_SET3
201 n12 45454464
MAIN_TEST_SET4
302 k32 36545445
如何显示?
感谢。
答案 0 :(得分:2)
print_r($users)
这将以直观的方式递归打印您的数组。请参阅手册:http://us2.php.net/manual/en/function.print-r.php
如果你想以你在上面格式化的特定方式打印它,你将不得不编写一个使用foreach循环语法的自定义函数,如下所示:
<?php
echo "<table>";
foreach($users as $testSetName=>$arrayOfTestCases){
echo "<tr><td>".$testSetName."</td></tr>";
foreach($arrayOfTestCases as $k=>$arrayOfTestCaseFields){
//$arrayOfTestCaseFields should be an array of test case data associated with $testSetName
$i = 0;
foreach($arrayOfTestCaseFields as $fieldName => $fieldValue){
//$fieldValue is a field of a testcase $arrayOfTestCaseFields
if($i == 0){
//inject a blank table cell at the beginning of each test case row.
echo "<tr><td> </td>";
$i++;
}
echo "<td>".$fieldValue."</td>";
}
echo "</tr>";
}
}
echo "</table>";
?>
您的数据应按如下方式组成:
$tset = "MAIN_TEST_SET";
$gettc = "101";
$getbid = "b12";
$getresultsid = "4587879";
$users[$tset] = array();
$users[$tset][] = array( "testcase"=>"$gettc",
"buildid"=>"$getbid",
"resultsid"=>"$getresultsid"
);
$users[$tset][] = ... and so forth ...
答案 1 :(得分:1)
要修复您提供的数据结构(正如Victor Nicollet在评论中提到的那样),您需要这样的内容:
$users = array(); // Create an empty array for the users? (Maybe testsets is a better name?)
$testset = array(); // Create an empty array for the first testset
// Add the test details to the testset (array_push adds an item (an array containing the results in this case) to the end of the array)
array_push($testset, array("testcase"=>"101", "buildid"=>"b12", "resultsid" => "4587879"));
array_push($testset, array("testcase"=>"102", "buildid"=>"b13", "resultsid" => "4546464"));
// etc
// Add the testset array to the users array with a named key
$users['MAIN_TEST_SET'] = $testset;
// Repeat for the other testsets
$testset = array(); // Create an empty array for the second testset
// etc
当然,还有更多创建数据结构的方法,但这个方法看起来/我看起来最清晰。
使用类似的方法使用上述数据结构创建HTML表。
echo "<table>\n";
foreach($users as $tsetname => $tset)
{
echo '<tr><td colspan="3">'.$tsetname.'</td></tr>\n';
foreach($tset as $test)
echo "<tr><td>".$test['testcase']."</td><td>".$test['buildid']."</td><td>".$test['resultsid']."</td></tr>\n";
}
echo "</table>\n";
第一个foreach迭代你的测试集,第二个forete迭代测试集中的测试。
答案 2 :(得分:0)
对于简短的非自定义输出,您可以使用:
print_r($users)
或者,您可以使用嵌套循环。
foreach($users as $key => $user) {
echo $key . "<br />"
echo $user["testcase"] . " " . $user["buildid"] . " " . $user["resultsid"];
}
如果您没有输出到html,请将<br />
替换为“\ n”