2
我想發送一個JSON文件來做一些測試。我有一個簡單的測試文件來創建一個多維數組。下面是測試文件:爲什麼json_encode/decode這樣配置我的數組? PHP
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$user['Mongo'] = null;
$user['Facebook'] = 12345;
$user['Twitter'] = null;
$user['Foursquare'] = null;
$user['Google'] = null;
$user['Name'] = "Bill Gates";
$user['Sex'] = 'M';
$user['Age'] = 26;
$user['Birthday'] = "1985-08-13";
$user['Friends'][0]['Mongo'] = null;
$user['Friends'][0]['Facebook'] = 123456;
$user['Friends'][0]['Twitter'] = null;
$user['Friends'][0]['Foursquare'] = null;
$user['Friends'][0]['Google'] = null;
$user['Friends'][0]['Name'] = "John Smith";
$user['Friends'][0]['Relationship'] = "Open";
$user['Friends'][1]['Mongo'] = null;
$user['Friends'][1]['Facebook'] = 1234567;
$user['Friends'][1]['Twitter'] = null;
$user['Friends'][1]['Foursquare'] = null;
$user['Friends'][1]['Google'] = null;
$user['Friends'][1]['Name'] = "Martina McBride";
$user['Friends'][1]['Relationship'] = "Open";
$user_json = json_encode($user);
$call = curl_init('http://MY_IP_HERE/user_login.php');
curl_setopt($call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($call, CURLOPT_POSTFIELDS, $user_json);
curl_setopt($call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($call, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '.strlen($user_json)));
$result = curl_exec($call);
curl_close($call);
echo $result;
?>
我試圖檢索文件,像這樣:
<?php
include_once('interaction_class.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
$user = json_decode($rawData);
if ($user['Mongo'] == null)
{
$user_id = $interaction->new_guest($user);
}
//...Other stuff...
我得到關於類stdClass的對象的錯誤在我的if語句行。所以,我做了的var_dump(),這是結果:
object(stdClass)#1 (10)
{
["Mongo"] => NULL
["Facebook"] => int(12345)
["Twitter"] => NULL
["Foursquare"] => NULL
["Google"] => NULL
["Name"] => string(15) "Bill Gates"
["Sex"] => string(1) "M"
["Age"] => int(26)
["Birthday"] => string(10) "1985-08-13"
["Friends"] => array(2)
{
[0] => object(stdClass)#2 (7)
{
["Mongo"] => NULL
["Facebook"] => int(123456)
["Twitter"] => NULL
["Foursquare"] => NULL
["Google"] => NULL
["Name"] => string(10) "John Smith"
["Relationship"] => string(4) "Open"
}
[1] => object(stdClass)#3 (7)
{
["Mongo"] => NULL
["Facebook"] => int(1234567)
["Twitter"] => NULL
["Foursquare"] => NULL
["Google"] => NULL
["Name"] => string(15) "Martina McBride"
["Relationship"] => string(4) "Open"
}
}
}
我的問題是,爲什麼我不能訪問的信息,我做了json_decode(後),像這樣:
$thing['Key']
爲什麼它把它解碼成一個Object而不是一個數組?
在此先感謝您的幫助!