ConorReidd ConorReidd - 2 months ago 7
JSON Question

Removing an array from a PHP JSON object

So a bit of background information is I'm creating a web app and I have 50~ arrays that I'm currently using what I get from an API, I've created a script to find the arrays that I don't need lets call them "bad arrays" but the problem is I'm unsure how I can filter these arrays out with the method I'm using to search through them

I'm searching through them with this script

$tagItems = [];
foreach($tags['items'] as $item) {
if (!$item['snippet']['tags'] || !is_array($item['snippet']['tags'])) {
continue;
}
foreach($item['snippet']['tags'] as $tag) {
$tag = strtolower($tag);
if (!isset($tagItems[$tag])) {
$tagItems[$tag] = 0;
}
$tagItems[$tag]++;
}
}


But let's say I didn't want it to include the 8th array and the 15th array

$tags['items'][8]['snippet']['tags'];
$tags['items'][15]['snippet']['tags'];


I want these to be removed from the original
$tags
array. How can i achieve this?

EDIT: This needs to be dynamic. I do not know if there are going to be 45/50 arrays that will need removing or just 2/50. the array that needs removing can be reffered to as
$index


I have a script which determines what array(s) need to be removed

$i = 0;
while ($i <= 50) {
$x = 0;
while ($x <= 50) {
if ($tags['items'][$i]['snippet']['channelId'] == $tags['items'][$x]['snippet']['channelId']) {
if ($x < $i) {
break;
} else {
echo $x.", ";
break;
}
}
$x++;
}
$i++;
}


I'm going to edit this a little more to provide some extra information that may be useful. My overall goal is to use the YouTube API to remove all but the first array of tags where the channel id appears multiple times. I'm using a script which finds all the array numbers that dont need to be removed an URL.

Answer

You can check for the array key

$tagItems = [];
$toRemove = array(8,15);
foreach($tags['items'] as $key => $item) {
    if(in_array($key,$toRemove)){
        continue;
    }
    if (!$item['snippet']['tags'] || !is_array($item['snippet']['tags'])) {
        continue;
    }
    foreach($item['snippet']['tags'] as $tag) {
        $tag = strtolower($tag);
        if (!isset($tagItems[$tag])) {
            $tagItems[$tag] = 0;
        }
        $tagItems[$tag]++;
    }
}