开发者

Can I do this with a single loop?

开发者 https://www.devze.com 2023-03-25 11:27 出处:网络
I have an array of \"striuctures\", let\'s say each lookss like $a[\'field_1\'] = \'value 1\'; $b[\'field_1\'] = \'value 2\';

I have an array of "striuctures", let's say each lookss like

$a['field_1'] = 'value 1';
$b['field_1'] = 'value 2';
$c['field_1'] = 'value 3';

and I store it in a MySql database.

Then later, I want to make a comparission against an array $b, which has the same keys and I want to ask

for each $a
   is there a $a['field_1'] where 'value X' == the value of $b['field_1'] ?

Can I avoid

for ($i = 0; $i < count($a); $i++)       
  for ($j = 0; $j < count($b); $j++)     
     if ($a[$i]['field_1'] == $b[$j]['field_1'])  
         &hellip;  

I would also like to do it in reverse.

Is there any built-in funct开发者_如何学JAVAion which I am overloooking, or must I go with two loops?

(btw, I am not using foreach because I want to pass $a by reference into a function and that gave me problems with foreach but not with a for loop -- for some reason which I can't fathom)


Try this:

foreach($a as $i => $val) {
    if(in_array($val, $b)) {
         doSomething($a, $i);
    }
}

If you need the location in B too, use this:

foreach($a as $i => $val) {
    $j = array_search($val, $b)
    if($j !== FALSE) { // note operator MUST be !==
         doSomething($a, $i, $b, $j);
    }
}

I should warn you it's just concealing the second loop, but it may be optimized this way.

Also, I used the foreach, because it should work fine the way I have it here. Feel free to change it back if necessary.


You can check that in MySQL using a query similar to this:

mysql_query('SELECT id FROM table WHERE field_1="' . $b['field_1'] . '";');


Try this:

<?php

    $array1 = array("value1", "value2", "value3");
    $array2 = array("value1", "value2", "value3");

    if (empty(array_diff($array1,$array2))) {
        echo "Arrays are equal!";
    }
    else echo "Arrays are NOT equal!";

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消