[英]Delete value in array and in array Laravel
I have array 我有阵列
Product:[
{
content:'',
tag:[
{
name:'a',
},
{
name:'b'
}
]
}
]
And i have value x = 'a'
我有价值
x = 'a'
I need delete name in tag
in array product
where name == x
我需要删除
name == x
数组product
中的tag
name == x
I used two foreach, one foreach loop Product and one foreach loop tag, then checking condition if(name == x)
and delete item 我使用了两个foreach,一个foreach循环Product和一个foreach循环标记,然后检查条件
if(name == x)
并删除item
Code 码
$tag = 'a'
foreach($blogs as $blog) {
foreach(json_decode($blog->tag) as $detail_tag) {
if($detail_tag == $tag) {
delete($detail_tag);
}
}
}
However, I mean function have some error ( I write code on paper and I don't test :( ) and I mean it no performance @@. Thanks 但是,我的意思是功能有一些错误(我在纸上写代码,我不测试:()我的意思是没有性能@@。谢谢
json_decode()
function. json_decode()
函数将JSON对象转换为数组。 Second parameter in this function is set to true
, in order to convert the JSON into associative array. true
,以便将JSON转换为关联数组。 foreach
you need to access key as well, in order to unset()
the value. foreach
您还需要访问键,以便unset()
值。 json_encode()
function. json_encode()
函数将数组转换回JSON对象。 Try: 尝试:
$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.