Jump to content

[SOLVED] Array matching..


spfoonnewb

Recommended Posts

I have been trying to get this to work for a while now.

 

What I am trying to get this script to do is:

 

For each value in $array2, it should check $array1[VALUE-OF-ARRAY2] to see if $x (Defined elsewhere) is a match ($x would be "/", or "/main").

 

If a match is found it should output $var;

 

If a match is not found it should output "error";

 

Once it finds a match it should stop on the specific array.

Say it's on ("/", "/main", "/index"), and it matches "/main", it should not check "/index", it should exit after the match.

 

It should however return error for each of the rest of the values.

 

If there's a better way to do this let me know, I just can't seem to get it working 100% perfectly.

 

These are the arrays being used:

 

$array1 = array(
"main" => array("/", "/main", "/index"),
"me" => array("/me"),
);

 

$array2 = array("main", "me");

 

Here is the code that I was working on.

 

<?php
foreach ($array2 as $var) {
if (array_key_exists($var, $array1)) {
	foreach (array_values($array1[$var]) as $y) {
		if ($y == $x)) {
			echo $var;
			break;
		}
		else {
			echo "Error";
		}
	}
}
}
?>

Link to comment
https://forums.phpfreaks.com/topic/67000-solved-array-matching/
Share on other sites


foreach($array2 as $var) {
  foreach($array1[$var] as $y) {
    if($y == $x)
      echo $var;
    else
      echo 'Error';
  }
}

 

This code should be looping through everything and comparing them. The first foreach loop takes every value in $array2, and sets it to $var. For each value it finds, it runs another foreach statement inside that and compares $array1[$var] against $x

 

so if $array2 has 5 entries, and array1 has 10 entries, it is looping 50 times to compare each of the 5 values against each of the 10 values.

 

It takes the first values of $array2 and compares it against every values of $array1[$var], then it moves to the next one and keeps going until all values in $array2 have been compared against $array1[$var]

 

Don't know if this helps or not... but it's all I got right now.

 

:)

 

Nate

Link to comment
https://forums.phpfreaks.com/topic/67000-solved-array-matching/#findComment-336404
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.