dsgdhtr_43654 2014-03-24 17:45 采纳率: 100%
浏览 92
已采纳

PHP只解析数组中的第一个元素

I'm working on a periodic table, in which I retrieve all the elements from my database. I want to place the elements in their respective position in the periodic table.

E.g.: Hydrogen is in row 1, cell 1 - Helium is in row 1, cell 18. The cells between those two should therefore be blank.

The problem is, that when I run my for-loop and compare the position - which is stored in my database - and the ID I've given each cell (which is the same as the position-outcome from the database), it only parses the first element and then stops.

It returns the first one 1-1 (Helium - Row 1, cell 1) and parses it like it should. Then the next one, which would be 1-2 (Row 1, cell 2), and from here on it just stops.

This is my query

// SQL Query for retrieving elements
$query = "
    SELECT 
        id, name, symbol, row, cell
    FROM 
        elements
    ORDER BY
        id
";
$objResult = $objConnection->query($query);

while ($row = $objResult->fetch_assoc()) {
    // Creating two-dimensional, associative array containing each element
    $ele[] = array(
        'id' => $row['id'],
        'name' => $row['name'],
        'symbol' => $row['symbol'],
        'position' => $row['row'].'-'.$row['cell']
    );
}

And my for-loops

// Element counter
$cnt = 0;

// Creating tr's and td's
for($i = 1; $i <= 9; $i++) {
    echo '<tr>';
        for($h = 1; $h <= 18; $h++) {
            $cell = $i.'-'.$h;
            $pos = $ele[$cnt]['position'];

            echo '<td id="'.$cell.'">';
            if($pos == $cell) {
                echo $ele[$cnt]['symbol'];
            }
            echo '</td>';
            $cnt++;
        }
echo '</tr>';

I hope you can help me, cus I'm pretty stuck.

  • 写回答

1条回答 默认 最新

  • dsns47611 2014-03-24 17:58
    关注

    You should rethink your array and make it associative. Why don't you make the key of your array the field. like this:

    $ele[ $row['row'].'-'.$row['cell'] ] = array(
        'id' => $row['id'],
        'name' => $row['name'],
        'symbol' => $row['symbol']
    );
    

    and then in your loop you can easily find the required element:

    for($i = 1; $i <= 9; $i++) {
    echo '<tr>';
        for($h = 1; $h <= 18; $h++) {
            $cell = $i.'-'.$h;
    
            echo '<td id="'.$cell.'">';
            if(isset($ele[$cell]) {
                echo $ele[$cell]['symbol'];
            }
            echo '</td>';
            $cnt++;
        }
    echo '</tr>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog