【问题标题】:for inside for loop php not working for the two tablesfor inside for loop php 不适用于两个表
【发布时间】:2018-09-08 02:09:25
【问题描述】:

我有两个表,我想使用函数compare() 的特定比较来比较元素。问题是,我有两张表:一张是静态的,一张是动态的。我从第一个 table1 中获得了第一个元素 $results1[$i],并将它与 table2 中的第一个元素进行比较(我们假设 table2 在时间 0 有一个元素)。如果compare() 函数返回一个小于3 的数字,我将table1 的第一个元素添加到table2,然后我必须将table1 的第二个元素与table2 的all 元素进行比较。

for($i = 0; $i < count ( $results1 ); $i++) {
    echo ' value 1 : ' . $results1 [$i] . '  ';
    for($k = 0; $k < count ( $results2 ); $k++) {
        echo ' value 2 : ' . $results2 [$k] . '  ';
        compare($results1 [$i],$results2 [$k]);
    }   
}

function compare($element1_table1,$element2_table2){
    if ($results_of_comparison< 3){
        //we add element1 to table2 and 
       //then we compare the next element of table 1 with all elements of table2
    }
}

如何使用循环比较表 1 的下一个元素与表 2 的所有元素? 有人可以帮帮我吗?

【问题讨论】:

  • If result
  • 如果比较的结果是

标签: php mysql for-loop


【解决方案1】:

如果数组具有相同的结构,您可以使用array_diff() 输出仅包含在两个数组中的第一个中的条目

$results1   = array(1,2,3,4);
$results2   = array(1,2,5);

$difference = array_diff($results1, $results2);

这将返回

3, 4

如果数组具有相同的结构,您可以使用array_intersect() 输出两个数组中包含的条目

$results1   = array(1,2,3,4);
$results2   = array(1,2,5);

$difference = array_intersect($results1, $results2);

这将返回

1, 2

例子:

$static  = array(1, 4, 6, 9);
$dynamic = array();

foreach($anything as $value){
  $dynamic[] = $value;
}

$difference = array_intersect($static, $dynamic);

【讨论】:

  • 是的,但是我已经有了我的功能并且它工作了,当我将一个元素添加到 results2 时,我的循环出现了问题,我必须将 results1 的 element1 与 table2 的所有元素进行比较
  • 我编辑了我的帖子。您还可以返回两个数组中包含的那些元素。使用这两个函数,您可以轻松比较您的数组。
  • 是的,我已经在我的特定函数中使用了这些函数,我的问题是如何使用循环来比较 table1 的所有元素与动态 table2 的元素?
  • 不需要在循环内比较。你说的第一个数组是静态的。只需在循环中生成第二个(如果需要),如果两个数组都准备好,最后比较它们。
  • 我发布了一个例子
猜你喜欢
  • 2017-03-20
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多