我有一個對象 $myObject; 我試圖將 php 對象作為 json 返回,但它丟失了一些數據。這是 $myObject 的樣子:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList Object( [priceListId:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 32 [amounts:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( [0] => 1000 [1] => 2000 [2] => 3000 [3] => 4000 [4] => 5000 [5] => 6000 [6] => 7000 ) [amountsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( [1000] => 0 [2000] => 1 [3000] => 2 [4000] => 3 [5000] => 4 [6000] => 5 [7000] => 6 ) [periods:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( [0] => 10 [1] => 15 [2] => 20 [3] => 25 [4] => 30 ) [periodsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( [10] => 0 [15] => 1 [20] => 2 [25] => 3 [30] => 4 ) [amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 7000 [period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 30 [prices:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( ) )后 json_encode($myObject); 新數據看起來像這樣(截圖以獲得更好的 json 視圖):
1 回答

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
問題是json_encode
無法訪問私有屬性。
以下是您可以采取的一些解決方法:
將屬性轉換為公共
您可以在轉換之前使用反射類來轉換屬性可訪問性
例子:
$refObject = new ReflectionObject( $obj ); $refProperty = $refObject->getProperty( 'property' ); $refProperty->setAccessible( true );
您可以使用 Reflection 對象遍歷對象的屬性并調用所有 getter 將對象轉換為可以輕松轉換的數組結構
- 1 回答
- 0 關注
- 140 瀏覽
添加回答
舉報
0/150
提交
取消