Jump to content

Problem with multidimensional arrays and foreach

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
DEViANT

DEViANT

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 358 posts
Right, So I'm writing a little script for a project of mine and I've hit a dead end. I found a function that takes in a given string, removes common used English words, and then return an array filled with word names and word count. The structure for the array looks as follows :

array(X) {

  ["keyword"]=>

  int(X)

}


I then have a while loop that runs through a database, selects the text and loads it into the function with a new array. The structure for the array looks as follows :

array(X) {

  [X]=>

array(X) {

    ["keyword"]=>

    int(X)

}

}


Now that that's done, I'd like to copy that array to a new one that is beter structured than the one I get from the function. So I tried using foreach. My foreach statement looks like this:

for($x = 0; $x <= $z; $x++)

{

	foreach($tmp as $key1=>$val1)

	{

		foreach($val1 as $key2=>$val2)

		{

			$article[$x] = array('keyword'=>$key2,'value'=>$val2);

		}

	}

}


However, the array $article consists solely of the very last keyword and integer value of the $tmp array. Its like it only copies the very last entry of the $tmp array into every value of the $article array regardless of any of the control statements.

My function looks like this:

<?php

function extractCommonWords($string){

$stopWords = array('i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','your','www');

$string = preg_replace('/ss+/i', '', $string);

$string = trim($string); // trim the string

$string = preg_replace('/[^a-zA-Z0-9 -]/', '', $string); // only take alphanumerical characters, but keep the spaces and dashes too…

$string = strtolower($string); // make it lowercase

preg_match_all('/\b.*?\b/i', $string, $matchWords);

$matchWords = $matchWords[0];

foreach ( $matchWords as $key=>$item ) {

if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) {

unset($matchWords[$key]);

}

}  

$wordCountArr = array();

if ( is_array($matchWords) ) {

foreach ( $matchWords as $key => $val ) {

$val = strtolower($val);

if ( isset($wordCountArr[$val]) ) {

   $wordCountArr[$val]++;

   } else {

	$wordCountArr[$val] = 1;

   }

}

}

arsort($wordCountArr);

$wordCountArr = array_slice($wordCountArr, 0, 30);

return $wordCountArr;

}

?>


I've been struggling with this for a good three hours by now.. Is there anyone that can give me some insight as to what I'm doing wrong?

Any help much appreciated.
Thanks in advance

#2
DEViANT

DEViANT

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 358 posts
Nevermind. Worked my way arround it.