简体   繁体   中英

PHP check if array contains another array (two-dimensional)

I have a two-dimensional arrays:

$wall = [
    [1, 0, 1, 1, 0, 1],
    [1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1],
    ];

$brick1 = [
    [1, 1],
    [1, 1]
];

$brick2 = [
    [1],
    [1],
    [1],
];

I would like to find out if $wall contains arrays $brick1 or $brick2 and remove them from $wall if it is true.

The output should get something like that

$wall = [
    [1, 0, 0, 1, 0, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1],
    ];

I tried to work with subarrays separately and cut the entire array into pieces, but all this is obtained in the form of a heap of cycles in cycles. Looks like a code with a smell. Should there be a simple solution?

Any idea please?

In the example you gave, $brick1 shouldn't take any more than ten iterations (of two or fewer iterations) and $brick2 shouldn't take any more than five iterations (of three or fewer iterations).

Is this a scaled down example of the real thing? You're right, there are a lot of cycles involved, but on this kind of scale it's negligible. The number of iterations doesn't matter, so long as it's fast enough. Have you done any benchmarking?

The only other thing I can think of is converting the columns to strings, and then using str_replace() or strtr() on the strings and then converting them back into arrays.

So:

$wall = [
    [1, 0, 0, 1, 0, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1],
];

becomes:

$wallStr = [
    '100',
    '000',
    '000',
    '111',
    '011',
    '111',
];

It might be faster as there would be less iterations involved. Then again, it might not be. However, it would still be awkward handling bricks that are more than one column wide.

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