簡體   English   中英

php:使用對象創建數組或如何擺脫多余的引號符號

[英]php: Create array with ojects or how to get rid off extra quotes symbols

我在文件中存儲了一些數據,看起來像這樣

{"name":"name1","uuid":"uuid1"}
{"name":"name2","uuid":"uuid2"}

比用PHP我用下一個代碼將其轉換為JSON

$file = "someData.json";
$content = explode("\r\n", file_get_contents($file));

$output = array( 'someData' => array_values( array_filter($content) ) );

$output = json_encode($output);
echo $output;

在輸出中我得到對象

[ " {"name":"name1","uuid":"uuid1"},{"name":"name2","uuid":"uuid2"} " ]

而不是對象數組

[{"name":"name1","uuid":"uuid1"},{"name":"name2","uuid":"uuid2"}]

獲取帶有對象的數組或僅刪除那些前引號和后引號的最佳方法是什么?

您的問題下的評論是正確的。 您將忽略將json解碼為PHP數據結構的步驟,因此每個javascript對象僅被視為字符串,而不是您想要將其視為對象/哈希。

與其按照自己的方式展開,不如將其重寫為:

$ file = file_get_contents(“ someData.json”;)
$ content = json_decode($ file);
$ output = array('someData'=> array_values(array_filter($ content));
$ output = json_encode($ output);
echo $ output;

我知道這可能看起來很愚蠢,但確實可以使用預浸料代替。

$json = '[ " {"name":"name1","uuid":"uuid1"},{"name":"name2","uuid":"uuid2"} " ]";

preg_replace(array("/[ \" {/", "/} \" ]/"), array("[{", "}]"), $json);

感謝您的幫助。 我在php中不是很好,但是即使擺脫了示例中的錯誤,我也會做出其他決定。 現在,我以這種原始方式回顯純JSON,而不進行任何解碼/編碼:

$file = "file.json";
$content = file_get_contents($file);
$content = rtrim($content, ",\r\n");

$output = '
        {
            "someData": ['.$someData.']
        }
        ';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM