在php中显示数组的正确方法

时间:2011-10-26 10:13:28

标签: php arrays foreach

所以,我有这种类型的数组

$fields = array('result'=>234, '1'=>1, '2'=>2, '3'=>4, ....'20'=>5);

我将它显示在表格中,但'result'键必须是最后一列。 到目前为止,我已经使用过这种方法,但是只要我需要在“结果”之外添加其他键,问题就会到达表的末尾。

foreach($fields as $key=>$value) {
  if(strcmp('key', 'result') != 0)
    echo "<td>$value</td>";
  }
echo "<td>$fields['result']</td>";

我认为这是一个更好的方法。你觉得怎么样?

5 个答案:

答案 0 :(得分:3)

我假设您知道最后要显示的键的名称,因此您可以执行以下操作:

$result = $fields['result'];
$otherResult = $fields ['other_result'];
unset($fields['result'], $fields['other_result']);

foreach($fields as $key=>$value) {
    echo "<td>$value</td>";
}

echo "<td>$result</td>";
echo "<td>$otherResult</td>";

这仅适用于少量按键。

答案 1 :(得分:2)

// array of columns you want to add at the end of the table in sequence
// I used an array of columns and an exrta foreach loop to be able to support possible future more columns to be added
$last_cols = array('result'=>null, 'other'=>null);

foreach($fields as $key=>$value) {
    // check if current column is one of the cols to be added at the end
    if (in_array($key, array_keys($last_cols))) {
        $last_cols[$key] = $value;
        continue;
    }

    echo '<td>'.$fields['result'].'</td>';
}
// loop through last columns
foreach($last_cols as $col) {
    echo '<td>'.$col.'</td>'
}

答案 2 :(得分:1)

有更快的方法:

$result = $fields['result'];
$otherResult = $fields['otherResult'];

unset($fields['result'], $fields['otherResult']);
foreach($fields as $key=>$value) {
  echo '<td>' . $value . '</td>';
}

echo '<td>' . $result . '</td>';
echo '<td>' . $otherResult . '</td>';

每次都不要检查密钥。

但是,如果你真的想要 - 按照以下方式进行:

if( $key == 'result' )

答案 3 :(得分:1)

在这种情况下,您的数据结构不是很好。为什么不使用

$result = 123;

?或者包含$ result和$ value的简单对象:

class MyDataContainer {
   public $result = 0;
   public $values = array();
}

?我会推荐这个,因为它会更清洁。

答案 4 :(得分:0)

将第一个元素作为数组中的最后一个元素(因为您不使用问题中的键):

$fields = array('result'=>234, '1'=>1, '2'=>2, '3'=>4, ....'20'=>5);

$fields[] = array_shift($fields);

Demo

相关问题