[英]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.