简体   繁体   中英

Check if array key exists in a multidimentional array

I have an array that's generated using mysql like this:

$conn = connect();
$stmt = $conn->prepare("select id, type, status from arraytest");
$stmt->execute();
$myArray = $stmt->fetchAll();

When I do print_r($myArray) , I get this:

Array ( [0] => Array ( [id] => 3 [0] => 3 [type] => 0 [1] => 0 [status] => 0 [2] => 0 ) [1] => Array ( [id] => 6 [0] => 6 [type] => 0 [1] => 0 [status] => 1 [2] => 1 ) ) 

I can also access the array this way:

echo $myArray[0][0]. ' ' . $myArray[0][1]. ' ' . $myArray[0][2];
echo '<br>';
echo $myArray[1][0]. ' ' . $myArray[1][1]. ' ' . $myArray[1][2];

The table data is simple:

"id"    "type"  "status"
"3"    "0"      "0"
"6"    "0"      "1"

I need to run the array against a while loop and check if id from the array matches the $i . But how is this done with an array like this? I cant figure out? Can you please help?

while ($i <= 10) {
    echo $i;
    echo ((array_key_exists($i,$myArray)) ? ' OK <br>' : ' Fail <br>'); // I need to check if $i == id from the array. 
    $i++;
    echo '<br>';
}

Expected Output

1 Fail
2 Fail
3 OK
4 Fail
5 Fail
6 OK
//and so on
while ($i <= 10) {
    echo $i;
    echo ($i==$myArray[$i]['id']) ? ' OK <br>' : ' Fail <br>';
    $i++;
    echo '<br>';
}

Edit

After the edit to your Question, this is a different story. Try this:

while ($i <= 10) {
    echo $i;
    $msg=' Fail <br>';
    foreach ($myArray as $v)
        if ($i==$v['id']) $msg=' OK <br>';
    echo $msg;
    $i++;
    echo '<br>';
}

You can modify the following code to get that. This is the generic code

<?php

/**
 * Get list of all keys of a multidimentional array
 *
 * @param array $array Multidimensional array to extract keys from
 * @return array
 */
function array_keys_multi(array $array)
{
    $keys = array();

    foreach ($array as $key => $value) {
        $keys[] = $key;

        if (is_array($array[$key])) {
            $keys = array_merge($keys, array_keys_multi($array[$key]));
        }
    }

    return $keys;
}

This involves fairly minimal changes to your code:

while ($i <= 10) {
    echo $i;
    $matched = array_filter($myArray, function($record) use ($i) {
        return $record['id'] === $i;
    });
    echo !empty($matched) ? ' OK <br>' : ' Fail <br>';
    $i++;
    echo '<br>';
}

In each loop, $matched is set to the array of records where the id is equal to $i . This will be non-empty if there is a match, otherwise empty.

Of course you could also use a normal foreach loop to determine if there is a matching id.

http://www.php.net/manual/en/function.array-filter.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM