這是我在我的PHP文件:轉換對象
$session = $m->session;
$會話現在是:
object(stdClass)[31]
public 'id' => string '21112' (length=5)
public 'external_id' => string '' (length=0)
public 'sessiongroupid' => string '1843' (length=4)
public 'eventid' => string '5588' (length=4)
public 'order' => string '0' (length=1)
public 'name' => string 'Ferdau Conference' (length=17)
public 'description' => string 'Ferdau Conference' (length=17)
public 'starttime' => string '2013-04-18 18:00:00' (length=19)
public 'endtime' => string '2013-04-18 18:04:00' (length=19)
public 'speaker' => string '' (length=0)
public 'location' => string 'Waregem' (length=7)
public 'mapid' => string '0' (length=1)
public 'xpos' => string '0.000000' (length=8)
public 'ypos' => string '0.000000' (length=8)
public 'maptype' => string 'plan' (length=4)
public 'imageurl' => string '' (length=0)
public 'presentation' => string '' (length=0)
public 'organizer' => string '0' (length=1)
public 'twitter' => string '' (length=0)
public 'allowAddToFavorites' => string '0' (length=1)
public 'allowAddToAgenda' => string '0' (length=1)
public 'votes' => string '0' (length=1)
public 'url' => string 'http://ferdau.be' (length=16)
public 'venueid' => string '0' (length=1)
我想所有的信息發送給一個函數命名保存在我的JavaScript文件。像這樣:
echo '<a onclick="save('.$session.')" style="cursor:pointer;" class="metacell">
<img src="'.buildUri("images/icons/favorite.png").'" width="16" />
<span>Add to favorites</span>
</a>';
當我嘗試這個時,我總是得到一個錯誤,只有一個字符串可以發送。我怎樣才能將這個對象轉換爲我可以發送給我的JavaScript函數的東西?
我已經試過這沒有結果:$data = json_encode($session);
當我做$data = json_encode((array)$session)
我得到這個:
<a class="metacell" style="cursor:pointer;" ferdau.be","venueid":"0"})"="" \="" 18:04:00","speaker":"","location":"waregem","mapid":"0","xpos":"0.000000","ypos":"0.000000","maptype":"plan","imageurl":"","presentation":"","organizer":"0","twitter":"","allowaddtofavorites":"0","allowaddtoagenda":"0","votes":"0","url":"http:\="" 18:00:00","endtime":"2013-04-18="" conference","starttime":"2013-04-18="" conference","description":"ferdau="" id":"21112","external_id":"","sessiongroupid":"1843","eventid":"5588","order":"0","name":"ferdau="" onclick="save({">
'$ data = json_encode((array)$ session)' –
可能的重複。 http://stackoverflow.com/questions/4697656/using-json-encode-on-objects-in-php-regardless-of-scope – karmafunk
在PHP> = 5.4.0中有一個用於將對象序列化爲JSON的新接口: JsonSerializable – karmafunk