Removing an array from a PHP JSON object - php

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.

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]++;
}
}

Related

need an php loop for existing condition

I am looking for a PHP solution to use a loop to go through to capture all the data
Here is an example of a lookup without using a loop
if (array_key_exists('utf8String', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('printableString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('bmpString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('telextexString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
}
I need the loop to go through the entire array. For ONLY the first [ ] the loop should increase the integer [0] to 1, [2] and so forth until its gone through the whole lot. In case you are wondering, the second [ ] is always [0] so that needs to remain as is.
Right now I am copying/pasting the above about 20 times and manually updating the number in the first box but I am hoping there is a more elegant way to achieve that.
-- MORE CONTEXT --
-- WORKING CODE -- offered by #Ghost
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
$exists = array('utf8String', 'printableString', 'teletexString');
$oid = array('id-at-stateOrProvinceName', 'id-at-countryName', 'id-at-localityName', 'id-at-commonName', 'id-at-organizationalUnitName');
for($i = 0; $i < $count; $i++) {
foreach($exists as $field) {
if(array_key_exists($field, $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'])) {
$value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'][$field];
echo $value, ' [',$field, ']',"\n";
}
}
}
You can just add another loop inside applying each field into array_key_exists, this applies to #Markus' idea anyway:
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
$exists = array('utf8String', 'printableString', 'teletexString');
$oid = array('id-at-stateOrProvinceName', 'id-at-countryName', 'id-at-localityName', 'id-at-commonName', 'id-at-organizationalUnitName');
for($i = 0; $i < $count; $i++) {
foreach($exists as $field) {
if(array_key_exists($field, $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'])) {
$value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'][$field];
$k = array_keys($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type']);
$oid = reset($k);
break;
}
}
}
[ EDIT: Please see the comments below. ] How about for simples...
$strings = ['utf8String', 'printableString' ... ];
foreach ($strings as $string) { // do your checks etc. }
I suppose you know how to increment a counter in a loop. $i++ and stuff, use [$i] wherever you need to increment the reference value in your $cert array. On match, break or continue in place of else if, depending on what exactly you need to accomplish here. Your objectives aren't too clear in the question, could share a bit more insight...

PHP testing for a next item

I can't figure out how to test if there's a next item in my array by using the key to test against. I think this is better explained in code. I know there's an easier way, I'm just a noob!
Basically I want to know if there is another item in the array and if so get the ->comp_id value.
for($i=0; $i<count($allcomps); $i++)
{
if($allcomps[$i]->comp_id == $curCompID)
{
$currentIndex = $i;
if($allcomps[$i+1]->comp_id == null )
{
echo "there isn't a next";
}
//echo $allcomps[$currentIndex+1]->comp_id;
}
}
You're already looping through allcomps, so why do you need a check for the next one?
Why not check within the loop?
for($i=0; $i<count($allcomps); $i++) {
if (isset($allcomps[$i]->comp_id) and $allcomps[$i]->comp_id == $curCompID) {
$currentIndex = $i;
}
}
I think a foreach might be even easier:
foreach($allcomps as $i=>$comp) {
if (isset($comp->comp_id) and $comp->comp_id == $curCompID) {
$currentIndex = $i;
}
}

PHP remove duplicate instances of dates in an array

I've tried various permutations of array_unique, and have searched other generic questions here on removing duplicate values from an array, but I can't quite set upon the answer I need. I have an array being passed of dates and values, and only want to view the DATE value once per date.
I'm using this for a Google chart and only want the date labels to show up once for each date. And I don't want to remove it entirely, because I want to be able to plot it on the chart.
So, an example array being passed:
["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]
And how I want it:
["June 4",30],["",35],["June 5",46],["",38.33],["",12]
Ideas?
Since you're using the data to feed into a google chart, I'm assuming that you know exactly what you need as far as output data. There's already some suggestions above for better ways to structure the data, but that probably won't work directly for a google chart.
How about this?
$data = [["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]];
$found = array();
foreach ($data as $i => $x) {
if (in_array($x[0], $found)) {
$data[$i][0] = '';
} else {
$found[] = $x[0];
}
}
print_r($data);
Basically, it's just building a list of dates that it's already seen. We loop through the data, and check if we've seen the date... if we have, we clear it from the data, otherwise we save it to the list so it'll be cleared next time.
Here's an alternate solution that only checks for duplicate dates that are consecutive, unlike the first solution that will remove all duplicates. This is probably closer to what you need for charting:
$data = [["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]];
$last = '';
foreach ($data as $i => $x) {
if ($x[0] == $last) {
$data[$i][0] = '';
} else {
$last = $x[0];
}
}
print_r($data);
In this case, we're just keeping track of the last date we've seen... and if our new date matches that, we clear it.
This is a possible solution for your problem, though I would recommend a re-construction as Patashu & Nikola R stated.
$untrimmed = [["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]];
$trimmed = stripDates($untrimmed);
function stripDates($dates) {
foreach( $dates as $key=>$date ) {
if ($key>0) {
if ($date[0] === $dates[$key-1][0]) {
$dates[$key][0] = "";
} else if($dates[$key-1][0] === "") {
for ($i = $key-1; $i > -1; $i--) {
if ($date[0] === $dates[$i][0]) $dates[$key][0] = "";
if ($dates[$key] != "") break;
}
}
}
}
return $dates;
}
// Note: This would require dates to be added chronically
//Output: ["June 4",30],["",35],["June 5",46],["",38.33],["",12]
I would recommend something like this:
$unconstructed = [["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]];
$constructed = constructAssoc($unconstructed);
function constructAssoc($dates) {
$constructed = array();
foreach( $dates as $index=>$date ) {
if (!array_key_exists($date[0], $constructed)) {
$constructed[$date[0]] = array("index"=>$index, "value"=>$date[1]);
} else {
array_push($constructed[$date[0], ["index"=>$index,"value"=>$date[1]]);
}
}
return $constructed;
}
//Output: ["June 4"=> [["index"=>0, "value"=>30], ["index"=>1, "value"=>35]], "June 5"=>[["index"=>2, "value"=>46], ["index"=>3, "value"=>38.33], ["index"=>4, "value"=>12]]]
Note: Added index in recommended solution if a more accurate re-construction is needed.

Foreach loop with extra filter -> need to identify last entry

I am trying to get the last entry in a foreach loop but struggling so far. My biggest problem is that once inside the foreach loop, I need to filter the array by eliminating every author who has 0 posts. This is my code so far:
$authors = get_users('orderby=nicename');
foreach ($authors as $author ) {
if ( count_user_posts( $author->id ) >= 1 ) { IF LAST {special <li>} else {normal <li> }
Can anyone shed some light on how to get the last entry in this scenario? Thanks
You should write a function to filter the array and then you can pop the last item off of it like this:
// use this section of code in PHP >= 5.3 - utilizes anonymous function
$filtered_array = array_filter($authors, function($author) {
if(count_user_posts($author->id) >= 1) return true;
return false;
});
// use this section of code for older versions of PHP - uses regular function
function author_filter($author) {
if(count_user_posts($author->id) >= 1) return true;
return false;
}
$filtered_array = array_filter($authors, 'author_filter');
// the rest is the same regardless of PHP version
$last_author = array_pop($filtered_array);
// output
foreach($filtered_array as $author) {
// regular output
}
// then do special output for $last_author
<?php
$numItems = count($arr);
echo "<ul>";
for($i = 0; $i < $numItems; $i++) {
if(as_zero_post){
//$i++;
continue;
}
$i == $numItems-1 ? "<li class='last-item'>".$arr[$i]."</li>" : "<li class='normal-item'>".$arr[$i]."</li>";
}
echo "</ul>"
?>

Build JSON with php echo statements

Am trying to build a JSON array from a php array
This is my function in my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
$last = end($data);
echo "[";
for($i = 0; $i < count($data); $i++) {
echo '{"user_id":"'.$data[$i][0]['user_id'].'",';
echo '"pheed_id":"'.$data[$i][0]['pheed_id'].'",';
echo '"pheed":"'.$data[$i][0]['pheed'].'",';
echo '"datetime":"'.$data[$i][0]['datetime'].'",';
if($i == count($data)) {
echo '"comments":"'.$data[$i][0]['comments'].'"}';
}else {
echo '"comments":"'.$data[$i][0]['comments'].'"},';
}
}
echo "]";
}
return false;
}
It returns a json array like this
[{"user_id":"9","pheed_id":"2","pheed":"This is my first real pheed, its got potential ","datetime":"1313188898","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"10","pheed":"Thank God for stackoverflow.com ","datetime":"1313358605","comments":"0"},]
But i cant seem to access it with jquery
I believe the problem rests with the trailing comma at the end of your array.
Rather than try to encode it yourself, use PHP's json_encode function. It's been tested and verified many, many times, so you don't have to reinvent the wheel.
Already voted up #derekerdmann, but thought I would add...
Your code will work, if you change:
if($i == count($data)) {
to
if($i == count($data) - 1) {
But, don't do that. If you are just putting everything from each member of the $data array into the json, then you should be able to just json_encode($data). If you are only pulling out certain parts, then build up a secondary array of your filtered data and json_encode that instead.
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
$filtered_items = array();
foreach ($data as $member) {
$filtered_item = array();
$filtered_item['user_id'] = $member['user_id'];
$filtered_item['pheed_id'] = $member['pheed_id'];
...
...
$filtered_items[] = $filtered_item;
}
echo json_encode($filtered_items);
}
return false;
}

Categories