2013-03-27 43 views
1

我有,我想用PHP提取JSON文本文件中使用PHP

http://rh.ernestek.cz.cc/webeast/static.txt

读书,我想提取“ID”和“关键”

一个JSON文件表我通过ID和关键要循环,这样我可以产生像这样的表:

 
ID  Key 
1  9d07d681e0c1e294264724f7726e6f6f29 
3  9cd1e3a4a04b5208862c3140046f73b515 
... 

我尝试使用下面的代码,但没有运气来提取第一ID和关键了:

<?php 
    $json = file_get_contents('static.txt'); 
    $json_decoded = json_decode($json); 
    echo "ID: ".$json_decoded->static->1->id."<br />"; 
    echo "Key: ".$json_decoded->static->1->key."<br />"; 
    ?> 

有什么我错了吗? 有什么建议吗? 谢谢!

+0

正在显示什么?你能更新你的答案吗? – 2013-03-27 14:07:42

+0

我采纳了HamZa DzCyber​​DeV不错的代码,这里是结果:http://rh.ernestek.cz.cc/webeast/trial.php – user2215892 2013-03-29 09:33:16

回答

0

在阵列上通过在json_decode()使用true它将所有对象转换为数组:

$json = file_get_contents("http://rh.ernestek.cz.cc/webeast/static.txt"); 
$json_decoded = json_decode($json, true); // return array 

$table = array(); 
foreach($json_decoded["static"] as $array){ 
    $table[$array["id"]] = $array["key"]; 
} 

//creating the table for output 
$output = '<table border="1"><tr><td>ID</td><td>Key</td></tr>'; 
foreach($table as $id => $key){ 
    $output .= "<tr><td>$id</td><td>$key</td></tr>"; 
} 
$output .= '</table>'; 
echo $output; 
+0

非常感谢。 我很抱歉,但我真的不明白这行是做什么“$ table [$ array [”id“]] = $ array [”key“];” 它打开一个2维数组与ID和密钥? 如果现在我希望我的表只包含json文件中“catched:0”的条目,应该如何编辑代码? 再次感谢! – user2215892 2013-03-27 15:06:32

+0

@ user2215892'$ array [“id”]'是ID,'$ array [“key”]'是KEY的权利?我创建了一个空数组'$ table',通过执行以下'$ table [$ array [“id”]] = $ array [“key”];'我将ID分配为数组的键并给它的值KEY。你会明白,如果你尝试以下'回声'

'; print_r($table);echo '
';' – HamZa 2013-03-27 15:11:38

+0

对不起,我问了一个愚蠢的问题。明白你的意思。谢谢! 此方法的工作原理很简单,因为id是一个数字,它只是一个简单的数组。 非常感谢!你从编辑表格中拯救了我的夜晚。 :) – user2215892 2013-03-27 15:18:46

1

解码的JSON作为数组(传递true作为第二个参数),和环像这样

<?php 
$json = file_get_contents('static.txt'); 
$json_decoded = json_decode($json, true); 
foreach ($json_decoded['static'] as $item) { 
    echo 'ID: ', $item['id'], '<br/>'; 
    echo 'Key: ', $item['key'], '<br/>'; 
} 
+0

非常感谢! 工程就像一个魅力! – user2215892 2013-03-27 15:01:18