0

我有 3 个不同的查询,它们从数据库返回 entity_id。

这是输出

[1237,1238,1279,1292,2676,2857,2924,2928]

[2688,2690,2692,2693,2694,2695,2696,2697,2698,2773,2774,2775,2859,2872,2873,2880,2881,2882,2883,2884,2885,2886,2887,2888,2889,2890,2891,2892,2893,2894,2928,2929]

[2629,2642,2676,2688,2690,2692,2693,2694,2695,2696,2697,2698,2773,2774,2775,2847,2848,2849,2850,2851,2852,2853,2854,2856,2857,2858,2859,2872,2873,2874,2875,2876,2877,2878,2879,2880,2881,2882,2883,2884,2885,2886,2887,2888,2889,2890,2891,2892,2893,2894,2907,2908,2918,2919,2920,2921,2922,2924,2925,2928,2929,2930,2931]

所以这会返回[2928]

是否有一个快速的 PHP 数组合并保留每 3 个数组中的 ID?

这是我的代码:

$location = "%".$_POST['location']."%";
$duration = $_POST['duration'];
$level = $_POST['level'];
$mysqli = new mysqli("localhost", "root", "password", "test");
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

if ($stmt = $mysqli->prepare("SELECT entity_id FROM  field_data_field_location WHERE field_location_value LIKE ?")) {
    $stmt->bind_param( "s", $location);
    $stmt->execute();
    $res = $stmt->get_result();
    $i = 0;
    $locationarray = array();
    while ($row = $res->fetch_assoc())
    {
        $locationarray[$i] = $row['entity_id'];
        $i = $i + 1;
    }
    echo json_encode($locationarray);
    $stmt->close();
}

if ($stmt2 = $mysqli->prepare("SELECT entity_id FROM  field_data_field_duration WHERE field_duration_value = ?")) {
    $stmt2->bind_param( "i", $duration);
    $stmt2->execute();
    $res2 = $stmt2->get_result();
    $j = 0;
    $durationarray = array();
    while ($row2 = $res2->fetch_assoc())
    {
        $durationarray[$j] = $row2['entity_id'];
        $j = $j + 1;
    }
    echo json_encode($durationarray);
    $stmt2->close();
}

$sql3="SELECT entity_id FROM  field_data_field_level";
if ($level!=="All") $sql3.= " WHERE field_level_value = ?";
if ($stmt3 = $mysqli->prepare($sql3)) {
    if ($level !=="All") $stmt3->bind_param( "s", $level);

    $stmt3->execute();

    $res3 = $stmt3->get_result();

    $k = 0;
    $levelarray = array();
    while ($row3 = $res3->fetch_assoc())
    {
        $levelarray[$k] = $row3['entity_id'];
        $k = $k + 1;
    }
    echo json_encode($levelarray);
    $stmt3->close();
}
4

3 回答 3

3

发现array_intersect()

$result = array_intersect($array1, $array2, $array3);
于 2013-11-07T13:28:27.287 回答
2

您正在寻找array_intersect()

array_intersect() 返回一个数组,其中包含所有参数中存在的 array1 的所有值。请注意,密钥是保留的。

于 2013-11-07T13:28:14.500 回答
0

以下是有关 array_intersect() 的答案,但在这种情况下,最好使用像这样的正确 SQL 查询

SELECT entity_id 
FROM  field_data_field_location 
WHERE   field_location_value LIKE ?
    AND field_duration_value = ?
-- and optional:
    AND field_level_value = ?
于 2013-11-07T13:36:37.993 回答