我有数组
Product:[
{
content:'',
tag:[
{
name:'a',
},
{
name:'b'
}
]
}
]
我有价值的x = 'a'
我需要删除数组product
中的tag
中的名称,其中name == x
我使用了两个foreach,一个foreach循环产品和一个foreach循环标记,然后检查条件if(name == x)
和delete项
代码
$tag = 'a'
foreach($blogs as $blog) {
foreach(json_decode($blog->tag) as $detail_tag) {
if($detail_tag == $tag) {
delete($detail_tag);
}
}
}
然而,我的意思是函数有一些错误(我在纸上写代码,我不测试:( ),我的意思是它没有性能@@。谢谢
发布于 2018-10-07 23:48:48
json_decode()
函数将JSON对象转换为数组。此函数中的第二个参数被设置为true
,以便将JSON转换为关联数组。然后foreach
中,您还需要访问key,以便对值进行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);
}
https://stackoverflow.com/questions/52690041
复制相似问题