在PHP後端和客戶端資料互動的過程中,JSON資料中有時格式不定,一會兒是數組,一會兒是對象,弄得客戶端開發人員要崩潰的感覺。
因此,前後端相關人員先對PHP的json_encode函數原理有必要的了解是最重要的一環。
PHP中的array是個萬能的資料結構,並不像其它語言根據需要的場景會定義很多約束性的資料類型來描述結構,所以PHP程式設計師是很難給客戶端人員講清楚回傳的是什麼結構的資料的。
也就變成明明是透過PHP的陣列資料編碼成json的,但輸出值有時是陣列、有時是物件的情況。
<code><span><?php</span><span>/*</span><span>如果你想生成一个json格式的数组格式(Vector)而非对象格式(Map)的,那么数据的下标:</span><span>必须是数字索引,</span><span>必须从0开始,</span><span>必须从小到大依次增加、中间不可以跳跃、顺序不可变动.</span><span>*/</span><span>//符合数组</span><span>$vector</span> = <span>[</span><span>12</span><span>,</span><span>23</span><span>,</span><span>18</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$vector</span><span>);</span><span>//符合数组</span><span>$vector2</span> = <span>[</span><span>0</span> => <span>12</span><span>,</span><span>1</span> => <span>23</span><span>,</span><span>2</span> => <span>18</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$vector2</span><span>);</span><span>//不符合数组,下标有跳跃</span><span>$map</span> = <span>[</span><span>0</span> => <span>12</span><span>,</span><span>1</span> => <span>23</span><span>,</span><span>2</span> => <span>18</span><span>,</span><span>4</span> => <span>20</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$map</span><span>);</span><span>//不符合数组,下标顺序不对</span><span>$map</span> = <span>[</span><span>0</span> => <span>12</span><span>,</span><span>1</span> => <span>23</span><span>,</span><span>3</span> => <span>18</span><span>,</span><span>2</span> => <span>20</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$map</span><span>);</span><span>//不符合数组,下标没有从0开始</span><span>$map_1</span> = <span>[</span><span>1</span> => <span>'111'</span><span>,</span><span>2</span> => <span>'asdfa'</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$map_1</span><span>);</span><span>//典型的对象格式</span><span>$map_2</span> = <span>[</span><span>'abc'</span> => <span>1</span><span>,</span><span>'de'</span> => <span>2</span><span>,</span><span>'fi'</span> => <span>null</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$map_2</span><span>);</span><span>/**</span><span> * 请注意上面的变量命名,对应于Hack中的概念,Vector和Map为两种数据集合类型</span><span> * 如果你需要将"索引数组"强制转化成"对象",可以这样写</span><span> * json_encode((object) $a);</span><span> * 或</span><span> * json_encode ($a, JSON_FORCE_OBJECT);</span><span> *</span><span> */</span></span></code>
解決方案是什麼?
就是透過PHP封裝Vector和Map這兩種資料結構的類,在建構json輸出結構時,以這兩種類型做封裝與轉換,來確保結構的確定性。
以上就介紹了物件數組 PHP JSON數組與物件的理解,包括了物件數組方面的內容,希望對PHP教程有興趣的朋友有所幫助。