2017-03-11 146 views
0

我的代碼在某種程度上工作,因爲它將我的數組回顯出來 - 但問題是,它會回顯所有字段。PHP Array to HTML Table問題

我想只顯示名稱,培訓師和狀態字段。我無法理解如何去做。

陣列

[{ 
id: "8001073", 
name: "Castarnie", 
silk: "c20170311her/00829186.jpg", 
cloth_number: "4", 
jockey: "Harry Cobden", 
trainer: "Robert Walford", 
weight_value: "165", 
weight_unit: "pounds", 
form: "P-2P2PF", 
bred: "GB", 
last_run: "21", 
status: "WINNER" 
}, 
{ 
id: "7164976", 
name: "Try It Sometime", 
silk: "c20170311her/00026136.jpg", 
cloth_number: "8", 
jockey: "Mikey Hamill", 
trainer: "Sheila Lewis", 
weight_value: "140", 
weight_unit: "pounds", 
form: "654529", 
bred: "IRE", 
last_run: "20", 
status: "LOSER" 
} 
] 

和PHP代碼看起來像

<?php if (count($obj) > 0): ?> 
<table> 
    <thead> 
    <tr> 
     <th><?php echo implode('</th><th>', array_keys(current($obj))); ?></th> 
    </tr> 
    </thead> 
    <tbody> 
<?php foreach ($obj as $row): array_map('htmlentities', $row); ?> 
    <tr> 
     <td><?php echo implode('</td><td>', $row); ?></td> 
    </tr> 
<?php endforeach; ?> 
    </tbody> 
</table> 
<?php endif; ?> 
+0

你'PHP'功能請。 –

+0

它來自json api $ jsondata = file_get_contents($ api_url); $ obj = json_decode($ jsondata,true); – BCLtd

回答

0

它沒有意義調用array_map()因爲你只修改每一個值的每一行與htmlentities顯示其中三個 - 只修改你要顯示的內容。

代碼:(Demo

$json_data=file_get_contents($api_url);  
$objects=json_decode($json_data); 
if(is_array($objects) && sizeof($objects)){ 
    echo '<table><thead><tr>'; 
     echo '<th>Name</th><th>Trainer</th><th>Status</th>'; 
    echo '</tr></thead><tbody>'; 
    foreach($objects as $row){ 
     echo '<tr>'; 
      echo '<td>',htmlentities($row->name),'</td>'; 
      echo '<td>',htmlentities($row->trainer),'</td>'; 
      echo '<td>',htmlentities($row->status),'</td>'; 
     echo '</tr>'; 
    } 
    echo '</tbody></table>'; 
}else{ 
    echo 'Invalid or empty json data received'; 
} 

輸出:產生該陣列

<table> 
    <thead> 
     <tr> 
      <th>Name</th> 
      <th>Trainer</th> 
      <th>Status</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td>Castarnie</td> 
      <td>Robert Walford</td> 
      <td>WINNER</td> 
     </tr> 
     <tr> 
      <td>Try It Sometime</td> 
      <td>Sheila Lewis</td> 
      <td>LOSER</td> 
     </tr> 
    </tbody> 
</table> 
1
$jsondata = file_get_contents($api_url); 
$obj = json_decode($jsondata, true); 
if (is_array($obj)){ 
    echo "<table>"; 
    echo "<th><td>Name</td><td>Trainer</td><td>Status</td></tr>"; 
    foreach ($obj as $row){ 
     array_map('htmlentities', $row); 
     echo "<tr>"; 
     echo "<td>".$row["name"]."</td>"; 
     echo "<td>".$row["trainer"]."</td>"; 
     echo "<td>".$row["status"]."</td>"; 
     echo "</tr>"; 
    } 
    echo "</table>"; 
} 
+0

感謝您花時間!真的很感激。它會得到500錯誤,但? – BCLtd

+0

剛剛得到它,謝謝! – BCLtd

+1

錯過了第二行的分號,修復後 – hendr1x