2016-01-06 33 views
0

我有这个数组里面的数据资料:找到一个数组

Array 
(
    [0] => Array 
     (
      [product_sequence] => 1 
      [quantity] => 1 
      [attributes] => Array 
       (
       ) 

     ) 

    [1] => Array 
     (
      [product_sequence] => 1 
      [quantity] => 1 
      [attributes] => Array 
       (
        [Colour] => Black 
       ) 

     ) 

) 

最新最好的方式,由product_sequence

我厌倦了使用搜索这个数组:

array_search('1', $_SESSION["cart"]) 

但这并不返回任何数据

+0

最好的方法是使用'foreach' –

+0

也是最快的方法吗? – charlie

+0

“搜索”是什么意思?你只想要有product_sequence = 1的数组? – AbraCadaver

回答

1

请试试这个

要找到符合搜索条件的值,你可以使用array_filter功能:

的价值:

$searchword = '1'; 
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); }) 

关键:

$searchword = 'last'; 
$matches = array(); 
foreach($example as $k=>$v) { 
    if(preg_match("/\b$searchword\b/i", $v)) { 
     $matches[$k] = $v; 
    } 
} 
0

您可以使用foreach或者你可以使用array_filter。一个简单的例子:

<?php 

$products = [ 
    [ 
     'product_sequence' => 1, 
    ], 
    [ 
     'product_sequence' => 1, 
    ], 
    [ 
     'product_sequence' => 2, 
    ] 
]; 


$productSequence = 1; 

$filteredProducts = array_filter($products, function($product) use ($productSequence) { 
    // only return elements that test `true` 
    return $product['product_sequence'] === $productSequence; 
}); 

print_r($filteredProducts); 

产量:

Array 
(
    [0] => Array 
     (
      [product_sequence] => 1 
     ) 

    [1] => Array 
     (
      [product_sequence] => 1 
     ) 

) 

更多阅读:

希望这有助于:)