我正在使用PHP 5.5.12
。PHP json_encode()數組的特定鍵
我有這樣的數組:
Array
(
[0] => Array
(
[user_id] => 3
[medicine_id] => 1
[time] => Array
(
[0] => stdClass Object
(
[event_type] => before_breakfast
[time] => 07:00:00
)
[1] => stdClass Object
(
[event_type] => after_breakfast
[time] => 07:30:00
)
)
)
[1] => Array
(
[user_id] => 3
[medicine_id] => 2
[time] => Array
(
[0] => stdClass Object
(
[event_type] => before_lunch
[time] => 13:00:00
)
[1] => stdClass Object
(
[event_type] => after_lunch
[time] => 14:00:00
)
)
)
[2] => Array
(
[user_id] => 3
[medicine_id] => 3
[time] => Array
(
[0] => stdClass Object
(
[event_type] => before_dinner
[time] => 20:00:00
)
[1] => stdClass Object
(
[event_type] => after_lunch
[time] => 21:00:00
)
)
)
)
欲json_encode()
每根級別的字段time
。
我試着使用:
foreach ($user_medicine_times as $user_medicine_key => $user_medicine_value) {
$user_medicine_value['time'] = json_encode($user_medicine_value['time'], true);
}
和:
foreach ($user_medicine_times as $user_medicine_key => &$user_medicine_value) {
$user_medicine_value['time'] = json_encode($user_medicine_value['time'], true);
}
但使用print_r($user_medicine_value)
,它返回相同的陣列。
我想要的結果如下:
Array
(
[0] => Array
(
[user_id] => 3
[medicine_id] => 1
[time] => "[{"event_type":"before_breakfast","time":"07:00:00"},{"event_type":"after_breakfast","time":"07:30:00"}]"
)
[1] => Array
(
[user_id] => 3
[medicine_id] => 2
[time] => "[{"event_type":"before_lunch","time":"13:00:00"},{"event_type":"after_lunch","time":"17:00:00"}]"
)
[2] => Array
(
[user_id] => 3
[medicine_id] => 3
[time] => "[{"event_type":"before_dinner","time":"20:00:00"},{"event_type":"after_lunch","time":"17:00:00"}]"
)
)
我怎樣才能實現這個結果?
你今天問了一個類似的問題,顯然刪除了這個問題,爲什麼?!如果你認爲你的問題沒有得到足夠的重視,我們有獎金。 – Daan
它更好地使一個新的數組只包含'[時間]'的值,然後使用'json_encode' –
我刪除的問題是有關過濾數組並替換特定鍵值的問題,我已經實現了。這是關於將特定鍵值轉換爲JSON。賞金2天后符合資格。如果在截止日期前工作,我無法等待那麼久。另外,如果沒有提供現有的解決方案,投票是傲慢,我認爲我已經刪除它。 – Dev