PHP - 比较2个多维数组中的值,然后输出所有相关值

时间:2018-01-26 17:30:25

标签: php mysql arrays multidimensional-array

尝试在PHP中比较两个多维数组。不幸的是,我无法加入两个表,因为服务器是MySQL 5.6和"字段" table字段值是一个JSON文档作为字符串。非常感谢任何帮助。

   $fields = array(
        array(
            'id' => 1,
            'option' =>'Field Label 1',
        ),
        array(
            'id' => 2,
            'option' =>'Field Label 2',
        ),
        array(
            'id' => 3,
            'option' =>'Field Label 3',
        ),
);
    $leads = array(

        array(
            'field_num' => 1,
            'name'=>Eddie,
        ),
        array(
            'field_num' => 3,
            'name'=>Mike,
        ),
        array(
            'field_num' => 2,
            'name'=>Frank,
        ),
        array(
            'field_num' => 2,
            'name'=>Mark,
        ),
        array(
            'field_num' => 2,
            'name'=>Dan,
        ),
);

输出应如下所示:
艾迪|现场标签1
迈克|现场标签3
弗兰克|现场标签2
马克|现场标签2
丹|现场标签2

这是我尝试过的。不用说,它没有用。

      foreach( $fields as $key => $field ) {
    if ($fields[id] === $leads[$key]['field_num']); {
        $mergedFieldID = $fields[id] === $leads[$key]['field_num'];
         echo $leads[$key]['name'] . "|" . $field['option'] . '<br>';
    }
}

3 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

function combine_arrays_by_keys(
    array $array1, 
    string $id1, 
    string $use1, 
    array $array2, 
    string $id2, 
    string $use2
) : array
{
    foreach ($array1 as $value) {
        $temp1[$value[$id1]] = $value[$use1];
    }
    foreach ($array2 as $value) {
        $temp2[$value[$id2]] = $value[$use2];
    }
    $result = [];
    foreach ($temp1 as $key => $value) {
        $result[] = [$temp1[$key], $temp2[$key]];
    }
    return $result;
}

演示:http://sandbox.onlinephpfunctions.com/code/74b94523078c7cc2e931e0892734b834f3dfa859

答案 1 :(得分:0)

如果你想尝试使用join的正确mysql查询...查看你的数据样本,mysql db的查询应该是

  select table2.name, table1.option
  from table1 
  inner join table2  on table1.id = table2.field_num

这个shoudl retunr你发布的结果

答案 2 :(得分:0)

这应该让你滚动:

$newarray = [];
foreach($leads as $lead) {
    $key = array_search($lead['field_num'], array_column($fields, 'id'));
    $newarray[] = array($lead['name'],$fields[$key]['option']);// put into new array
    echo $lead['name'] .'|'. $fields[$key]['option'] .'<br>';// or direct output
}
print_r($newarray);

输出:

Eddie | Field Label 1
Mike | Field Label 3
Frank | Field Label 2
Mark | Field Label 2
Dan | Field Label 2

Array (
    [0] => Array
        (
            [0] => Eddie
            [1] => Field Label 1
        )
    [1] => Array
        (
            [0] => Mike
            [1] => Field Label 3
        )
    [2] => Array
        (
            [0] => Frank
            [1] => Field Label 2
        )
    [3] => Array
        (
            [0] => Mark
            [1] => Field Label 2
        )
    [4] => Array
        (
            [0] => Dan
            [1] => Field Label 2
        )
    )