如何访问对象内的值?

时间:2011-07-04 10:37:44

标签: php json

{
   "http://url.com": {
      "id": "http://url.com",
      "shares": 11111
   }
}

我需要访问'id'和'shares',看起来像是正常的

($results->shares)

在这里不起作用,有什么建议吗?感谢。

使用完整代码进行编辑:

<?php 

include __DIR__ . '/config.php';

function do_curl($start_index, $stop_index) {

    // Do query here to get all pages with ids between start index and stop index

$sql = "SELECT * FROM mmakers WHERE id >= $start_index and id <= $stop_index";
$result = mysql_query($sql) or die(mysql_error());
    while ($row = mysql_fetch_array($result))
    {
        $fanpages_query[] = 'https://graph.facebook.com/?ids='.$row['domain'];
    }
    return $fanpages_query;

}


$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
$fanpages_count = count($fanpages);


$curl_arr = array();
$master = curl_multi_init();

for($i = 0; $i < $fanpages_count; $i++)
{
    $url = $fanpages[$i];
    $curl_arr[$i] = curl_init($url);
    curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($master, $curl_arr[$i]);
}
do {
    curl_multi_exec($master,$running);
} while($running > 0);


for($i = 0; $i < $fanpages_count; $i++)
{
    $results = json_decode(curl_multi_getcontent($curl_arr[$i]));

    $sql_mm = "SELECT * FROM mmakers WHERE domain='".($results->id)."'";
    $result_mm = mysql_query($sql_mm) or die(mysql_error());
    $row_mm = mysql_fetch_array($result_mm);

    if ($row_mm['type'] == 'auto') {
    $sql_d = "SELECT domain FROM domains_list WHERE used='no' AND directory='".$row_mm['directory']."' AND type='auto' ORDER BY rand() LIMIT 1";
    $result_d = mysql_query($sql_d) or die(mysql_error());
    $row_d = mysql_fetch_array($result_d);
    } else {
    $sql_d = "SELECT domain FROM domains_list WHERE used='no' AND directory='".$row_mm['directory']."' AND type='jaa' ORDER BY rand() LIMIT 1";
    $result_d = mysql_query($sql_d) or die(mysql_error());
    $row_d = mysql_fetch_array($result_d);
    }

    mysql_query("UPDATE mmakers SET shares = '".($results->shares)."' WHERE id='".$row_mm['id']."'") or die(mysql_error());

}

?>

6 个答案:

答案 0 :(得分:3)

我建议将JSON解码为数组:

$results = json_decode($json, true);

然后假设你不知道URL,你必须遍历数组:

foreach($results as $url => $data) {
    echo $url, ' shares: ', $data['shares'];
}

如果您知道该网址,则可以

$results['http://url.com']['shares'];

答案 1 :(得分:1)

试试这个:

$results->{"http://url.com"}->shares

答案 2 :(得分:1)

你忘记了一处房产。

echo $results->{"http://url.com"}->shares;

答案 3 :(得分:0)

您也可以这样做......

$results = json_decode($json, true);
echo $results[0]["shares"];

答案 4 :(得分:0)

$content = '{
   "http://url.com": {
      "id": "http://url.com",
      "shares": 11111
   }
}';

$object = json_decode($content);
$object->{'http://url.com'}->shares; //11111

答案 5 :(得分:0)

解码JSON时,将$assocjson_decode()的第二个参数)设置为true

$jsonData = json_decode($jsonText, true);
$url = 'http://url.com';
var_dump($jsonData[$url]['id']);
var_dump($jsonData[$url]['shares']);