Forum Moderators: coopster

Message Too Old, No Replies

Adding items to array in a foreach statement

Not looping as I would have hoped

         

ocon

1:28 am on Apr 8, 2010 (gmt 0)

10+ Year Member Top Contributors Of The Month



I am stuck, and so is my script.

I've been working on a script that goes through a MediaWiki install (such as Wikipedia) to recursively collect all articles in a category. I'm starting with the highest level category,

I'm using a $oApi->getCat function in the SxWiki library that lists all the contents of a category in an array.



$processing=$oApi->getCat("Art"); // I'm starting, with this highest level category.

foreach($processing as &$entry){ // I'm going through this array
if(substr($entry,0,9)!="Category:") $articles[]=$entry; // If the item doesn't start with "Category:" then its an article, and is being added to my article list
else{ // If its not an article, then its a Category
$temp=$oApi->getCat(substr($entry,9)); //I'm looking at the contents of this subcategory
foreach($temp as &$newentry) if(!in_array($newentry,$processing)) $processing[]=$newentry;}} // If its not already in there, I'm adding the item to my list.

$articles=array_unique($articles);

print_r($articles);


The problem right now is that even though I'm adding new items to the processing array, foreach doesn't pick it up. I've tried adding the function in some type of loop, but then I'm having problems with global variables, and the library I'm using.

I haven't been able to get there, but something that I'm worried about in the future is a looping effect if Category A is in

Readie

12:50 pm on Apr 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Rather than trying to control duplicate values in the for each loop, you could just use the array_unique() [uk.php.net] function after having built the arrays.

[edited by: Readie at 1:24 pm (utc) on Apr 8, 2010]

andrewsmd

1:21 pm on Apr 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm not really for sure if I understand what your problem is. Try using array_push on your last line of your loop.
foreach($temp as &$newentry) if(!in_array($newentry,$processing)) array_push($processing, $newentry);}}