我有数组
Product:[
{
content:'',
tag:[
{
name:'a',
},
{
name:'b'
}
]
}
]
我有值 x = 'a'
我需要删除 tag
数组 product
中的名称,其中 name == x
我使用了两个 foreach,一个 foreach 循环 Product 和一个 foreach 循环标签,然后检查条件 if(name == x)
并删除项目
代码
$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);
}
关于php - 删除数组和数组 Laravel 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52690041/