PHP数组2维,如何检查2个值是否在其内部和位置

时间:2018-06-11 02:36:41

标签: php arrays

我有一个二维数组如下:

$array2dimension = $result->fetch_all(MYSQLI_ASSOC);

Array
(
    [0] => Array
        (
            [time] => 12:00
            [box] => 3
            [user] => Laura
        )

    [1] => Array
        (
            [time] => 14:00
            [box] => 3
            [user] => John
        )

)

目前我有两个值,但有时我还有更多,其中两个有[box] ='3',但不同[时间](12:00和14:00) [time]和[box]的组合是唯一的,因此我可以找到该组合的一个或零记录。

我该怎么检查:

1)如果这个数组中有两个变量?例如。

$varTime = '14:00';
$box = 3;
in_array($varTime+$box, $array2dimension) -> this is wrong, I don't know how to apply it

2)这些数据的位置是什么?例如,在此示例中,它将是[1]

提前致谢, 菲利普

3 个答案:

答案 0 :(得分:1)

假设您的timestring

// what you are looking for
$time = '14:00';
$box = 3;

$found = 0;
$i = 0;

foreach($array2dimension as $row) {
    $time_i = $row['time'];
    $box_i = $row['box'];

    if ($time_i == $time && $box_i == $box) {
        $found = 1;
        break;
    }

    $i++;
}

if ($found == 1) {
    print "found in array element: $i";
}

答案 1 :(得分:1)

你可以推广自己的功能,因为据我所知,in_array不接受自定义比较器:

function inArr($arr2d, $targetTime, $targetBox) {
  foreach ($arr2d as $i => $e) {
    if ($e["time"] === $targetTime && $e["box"] === $targetBox) {
      return $i;
    }
  }

  return -1;
}

$array2dimension = [
  [
    "time" => "12:00",
    "box" => 3,
    "user" => "Laura"
  ],
  [
    "time" => "14:00",
    "box" => 3,
    "user" => "John"
  ]
];

echo inArr($array2dimension, "14:00", 3) . "\n";
echo inArr($array2dimension, "12:00", 3) . "\n";

输出:

PHP 7.0.8 (cli) (built: Jun 23 2016 23:39:14) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

1
0

答案 2 :(得分:1)

$expected_values = array('time' => '14:00', 'box' => 3);

$found_elements = array_filter($array2dimension, function($sub_array) use ($expected_values) {
    $intersection_count = count(array_intersect_assoc($sub_array, $expected_values));

    return $intersection_count == count($expected_values);
});

if (!empty($found_elements)) {
    $found_indexes = array_keys($found_elements);
}

我希望该片段可以帮助你。