Reputation: 51
I have array
Product:[
{
content:'',
tag:[
{
name:'a',
},
{
name:'b'
}
]
}
]
And i have value x = 'a'
I need delete name in tag
in array product
where name == x
I used two foreach, one foreach loop Product and one foreach loop tag, then checking condition if(name == x)
and delete 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
Upvotes: 4
Views: 302
Reputation: 28834
json_decode()
function. Second parameter in this function is set to true
, in order to convert the JSON into associative array.foreach
you need to access key as well, in order to unset()
the value.json_encode()
function.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);
}
Upvotes: 2