[英]Delete value in array and in array Laravel
我有陣列
Product:[
{
content:'',
tag:[
{
name:'a',
},
{
name:'b'
}
]
}
]
我有價值x = 'a'
我需要刪除name == x
數組product
中的tag
name == x
我使用了兩個foreach,一個foreach循環Product和一個foreach循環標記,然后檢查條件if(name == x)
並刪除item
碼
$tag = 'a'
foreach($blogs as $blog) {
foreach(json_decode($blog->tag) as $detail_tag) {
if($detail_tag == $tag) {
delete($detail_tag);
}
}
}
但是,我的意思是功能有一些錯誤(我在紙上寫代碼,我不測試:()我的意思是沒有性能@@。謝謝
json_decode()
函數將JSON對象轉換為數組。 此函數中的第二個參數設置為true
,以便將JSON轉換為關聯數組。 foreach
您還需要訪問鍵,以便unset()
值。 json_encode()
函數將數組轉換回JSON對象。 嘗試:
$tag = 'a';
foreach($blogs as $blog) {
// convert to array using json_decode() (second parameter to true)
$blog_arr = json_decode($blog->tag, true);
// Loop over the array accessing key as well
foreach( $blog_arr as $key => $detail_tag){
if ($detail_tag === $tag) {
// unset the key
unset($blog_arra[$key]);
}
// Convert back to JSON object
$blog_tag_modified = json_encode($blog_arr);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.