数组操作思想


array manipulation idea

我有两个数组。

$Array1 = array("Maza", "Nissan","Tacoma","Cobalt","Explorer");

第二个阵列是

array(
    (int) 0 => array(
        (int) 0 => 'In Stock',
        (int) 1 => 'Cars'
    ),
    (int) 1 => array(
        (int) 0 => 'In stock',
        (int) 1 => 'Cars/Toyota/Tacoma'
    ),
    (int) 2 => array(
        (int) 0 => 'Out of Stock',
        (int) 1 => 'Cars/Toyota/Celica'
    ),
    (int) 3 => array(
        (int) 0 => 'In Stock',
        (int) 1 => 'Cars/Ford/Fusion'
    ),
    (int) 4 => array(
        (int) 0 => 'Out of Stock',
        (int) 1 => 'Cars/Ford/Explorer'
    ),
    (int) 5 => array(
        (int) 0 => 'In Stock',
        (int) 1 => 'Cars/Chevy/Cobalt'
    ),
    (int) 6 => array(
        (int) 0 => 'In Stock',
        (int) 1 => 'Cars/Nissan'
    )
)

现在我想看看根据第一个和第二个阵列有没有库存的汽车。因此,对于Cobalt,它会将我退回库存,而对于Explorer,它会使我缺货。对于Mazda来说,它可以重新运行"请勿携带"。我感到困惑的是,是否用斜线"/"分解数组[1],然后查看它。还有其他更简单/更快的方法吗?感谢

试试这个:

$cars = array("Maza", "Nissan","Tacoma","Cobalt","Explorer");
$stocks=array(
    (int) 0 => array(
        (int) 0 => 'In Stock',
        (int) 1 => 'Cars'
    ),
    (int) 1 => array(
        (int) 0 => 'In stock',
        (int) 1 => 'Cars/Toyota/Tacoma'
    ),
    (int) 2 => array(
        (int) 0 => 'Out of Stock',
        (int) 1 => 'Cars/Toyota/Celica'
    ),
    (int) 3 => array(
        (int) 0 => 'In Stock',
        (int) 1 => 'Cars/Ford/Fusion'
    ),
    (int) 4 => array(
        (int) 0 => 'Out of Stock',
        (int) 1 => 'Cars/Ford/Explorer'
    ),
    (int) 5 => array(
        (int) 0 => 'In Stock',
        (int) 1 => 'Cars/Chevy/Cobalt'
    ),
    (int) 6 => array(
        (int) 0 => 'In Stock',
        (int) 1 => 'Cars/Nissan'
    )
);
$output=array();
foreach ($cars as $car) {
   foreach ($stocks as $stock) {
    if(in_array($car, explode('/', $stock[1]))){
        $output[$car]=$stock[0]; 
        break;
        }else{$output[$car]='Do not care';}
} 
}
echo '<pre>';
print_r($output);

这将打印:

Array
(
    [Maza] => Do not care
    [Nissan] => In Stock
    [Tacoma] => In stock
    [Cobalt] => In Stock
    [Explorer] => Out of Stock
)

也许

$Array1 = array("Maza", "Nissan","Tacoma","Cobalt","Explorer");
$secondarray = array(
    array('In Stock', 'Cars'),
    array('In stock', 'Cars/Toyota/Tacoma'),
    array('Out of Stock', 'Cars/Toyota/Celica'),
    array('In Stock', 'Cars/Ford/Explorer'),
    array('Out of Stock', 'Cars/Ford/Explorer'),
    array('In Stock', 'Cars/Chevy/Cobalt'),
    array('In Stock', 'Cars/Nissan'));
function findcar($car, $secondarray) {
    for($c = 0; $c <= count($secondarray); $c++) {
        if(strpos(strtolower($secondarray[$c][1]), strtolower($car)) > 0) {
                return $secondarray[$c][0];
        }
    }
}
echo findcar($Array1[1], $secondarray);

这将打印出In Stock,如果没有找到一辆车,它什么也不回。