简体   繁体   中英

PHP iterate multi dimensional array with missing rows

Suppose I have 2d array, where only some rows actually have some values in the columns, whereas other rows don't have anything.

For example: only rows 5 and 9 have some data, other rows are empty. Number of columns is fixed - 6

I have not declared any size for the 2D array.

I want to find all fields whose value is 10.

for ($t1=0; $t1 < count($array); $t1++) { 

    for ($t2=0; $t2 < 6; $t2++) { 

        if($array[$t1][$t2] == 10) {
            // do something
        }
    }
}

Now this code won't work because count($array) will be 2, so it will never iterate for rows 5 and 9.

I also need to get the index at which I found a match.

How can I write code to make it work in this case?

You can effectively use foreach in this case:

foreach($array as $s => $arrayElement) {
    for($t=0; $t<6; $t++) if ($arrayElement[$t] == 10) {
         // do something - $s is the row index, $t is the column index
    }
}

I think , you have a problem in defining array. May be , you can use this script.

<?php
$cars = array(
    array(
        "Volvo",
        22,
        18
    ),
    array(
        "BMW",
        15,
        13
    ),
    array(
        "Saab",
        5,
        2
    ),
    array(
        "Land Rover",
        17,
        15
    ),
    array(
        "Mercedes",
        22,
        19
    )
);

$length = count($cars);

for ($i = 0; $i < $length; $i++) {
    for ($j = 0; $j < 3; $j++) {
        echo $cars[$i][$j] . "</br>";
    }
}

?>

I hope , it will solve your problem.

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