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;
}
}
Related
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]++;
}
}
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...
I have managed to decode some JSON in PHP successfully (not as painful as I thought), but it's been such a long time since I've done any real PHP, my brain has drawn a blank on the following.
The decoded json looks like this
[Array]
item {
[0]
{
[live]=>
[name]=>Paul
[value]=>10
}
[1]
{
[live]=>1
[name]=>Fred
[value]=>32
}
and so on
The problem I'm having is this - I'm trying to iterate through the structure to test first if live==1 and then if it's the first live name, to output it as a selected value to a HTML drop down.
I'm currently trying like this
$t = 0;
$count = 0;
foreach($decode['items'] as $option=>$value)
{
print_r("option = $option\n");
if ($option=>isLive == 1)
{
print_r("isLive is true for $option[$count]['names']\n");
if ($t == 0)
{
echo "<option value=$option[name] selected>$value[name]</option>";
$t = 1;
}
else
echo "<option value=$option[name]>$value[name]</option>";
}
else
{
print_r("isLive is false for $option[$count]=>name\n");
}
$count++;
}
the problem is that I don't seem to be able to get the if statement correct for this to work. This is probably a seriously simple problem and will no doubt make me face palm, but I could do with a pointer in the right direction here!
If the json is like you showed us you could not iterate over anything with your foreach because your array does not contain a key named items.
Using the provided structure this should do the trick:
foreach($decode["item"] as $item) {
if($item->live == 1) {
...
} else {
...
}
}
If $item is not an object use $item['live'] instead.
P.S.: You should really turn error_reporting on. $option=>isLive is no valid syntax.
$t = 0;
$count = 0;
$arr = json_decode($json,true);
foreach($arr as $key=>$val)
{
print_r($key);
if($val['live'])
{
if($t == 0)
{
echo '<option value='.$val['name'].' selected>'.$val['name'].'</option>';
$t = 1;
}
else
{
echo '<option value='.$val['name'].'>'.$val['name'].'</option>';
}
}
else
{
echo $key.' not printed cause it hasn\'t live set to true';
}
$count++;
}
Here is my code :
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b-1);$i++)
{
for($j=1;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
I just want to know what's wrong in the above code ? because if i take 3 array values it works fine but for 4 its not working....can someone do the modification for the same code,and also please briefly explain why is it not working any issues with looping?I am not looking for different code.
You have mistakenly modified the bubble sort algorithm. Use standard one.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++) //Changes over here
{
for($j=0;$j<($b);$j++) //Changes over here
{
if($a[$j]>$a[$i]) //Changes over here
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
Why are you manually sorting when you have sort?
$a = array(10,8,6,5);
sort($a);
var_dump($a);
Similarly, why are you using temporary variables when you have list?
list($a[$i],$a[$j]) = array($a[$j],$a[$i]);
try below code may be that will help.
<?php
function pr($array = array())
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$a = array(10,8,6,5);
$b = count($a);
for($i=0;$i <= ($b-1);$i++)
{
for($j=0; $j < ($b);$j++)
{
if($a[$j] < $a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
pr($temp);
pr($a);
?>
<?php
$a=array(8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++)
{
for($j=0;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
The inner loop doesn't need to be executed n times (where n=number of elements to be sorted). Every time the outer loop executes, one more element at the end (for ascending order) is in the correct position. So, inner loop should not check those elements.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++){
for($j=0;$j<($b-$i);$j++){ // this change will save time
if($a[$j]>$a[$i]){
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
?>
I have programmed a script with the goto command but on the server where I want to execute the script there is a previous PHP version (<5.3), so I have to change the code. The structure of the code goes like that:
for($i = 0; $i < 30; $i++) // print 30 articles
{
$x = 0;
// choose a a feed from the db
// parse it
a:
foreach($feed->get_items($x, 1) as $item)
{
// create a unique id for the article of the feed
if($id == $dbid)
{
// if this id exists in the db, take the next article of the same feed which is not in the db
$x++;
goto a;
}
else
{
// print the original article you grabbed
}
} // end of foreach
} // end of for
I have tested everything. Do you have any ideas how can I retransform this code without goto in order to be executed properly???
This questions demonstrates why goto should be avoided. It lets you get away without thinking about the algorithm enough.
The standard way to do this is with a flag. I hope you were not expecting a "herezthecode kthxbai" sort of an answer, but in this case the best way to explain it would be to write the code -
for($i=0;$i<30;$++){
$x=0;
do {
$found = false;
foreach($feed->get_items($x,1) as $item){
// get $id
if($id==$dbid){
$found = true;
break;
}else{
// other things
}
}
$x++;
} while($found);
}
Without knowing how the ->get_items() call behaves you could use this brute-force method in lieu of the goto-switch:
for($i = 0; $i < 30; $i++)
{
$x = 0;
$a = 1;
while ($a--)
foreach($feed->get_items($x, 1) as $item)
{
if($id == $dbid)
{
$x++;
$a=1; break;
}
else
{
}
} // end of foreach
} // end of for
The label gets replaced by a while and a self-fulfulling stop condition. And the goto becomes a break and resets the $a stop condition.
Something like this would probably work...
function loop(){
foreach($feed->get_items($x,1) as $item){
if($id==$dbid){
$x++;
loop();
}else{
}
}
}
for($i=0;$i<30;$++){
$x=0;
loop();
}
I'm sorry, I removed all the comments, they were annoying.
Move the declaration of $x outside of the for loop and replace your label/goto combination with a break, like so...
$x=0;
for($i=0;$i<30;$++) //print 30 articles
{
foreach($feed->get_items($x,1) as $item)
{
// create a unique id for the article of the feed
if($id==$dbid)
{
//if this id exists in the db,take the next article of the same feed which is not in the db
$x++;
continue;
}
else
{
//print the original article you grabbed
}
} // end of foreach
}//end of for
Agree with unset - using break will break if loop and keep iterating through for loop