2016-02-08 41 views
1

多维数组的获取信息我有这种结构的数组:出1个特定项目

0 => 
    array (size=19) 
     'ArticleId' => int 10042 
     'Eanbarcode' => string '0000000010042' (length=13) 
     'Brand' => string 'Lazzo' (length=5) 
     'Season' => string 'SS16' (length=4) 
     'Subseason' => string '' (length=0) 

1 => 
    array (size=19) 
     'ArticleId' => int 10043 
     'Eanbarcode' => string '0000000010043' (length=13) 
     'Brand' => string 'Lazzo' (length=5) 
     'Season' => string 'SS16' (length=4) 
     'Subseason' => string '' (length=0) 

现在我想用ArticleId获得该文章的所有TE产品信息。我想我首先需要在文章中找到正确的密钥号码,然后从密钥中获取信息,但我无法弄清楚如何去做。

+0

你是如何得到数组? – AnkiiG

+0

从我的一个朋友那里得到了它,它从json文件中获得并且不能改变它。他说这是它,如果你var_dump它,我需要某些articleID的所有信息 – Dan

回答

1

您可以使用foreach循环来处理整个数组,然后用当前的代码挑出每个ArticleId

foreach ($array as $article) { 
    $articleId = $article['ArticleId']; 

    // do something with the ArticleId 
} 
1

的方法是做这样的事情......

function getArticle($articleIdToFind, $articles) { 
    foreach ($articles as $article) { 
     $articleId = $article['ArticleId']; 
     if ($articleId == $articleIdToFind) { 
      return $article; 
     } 
    } 
    return null; 
} 

这似乎有点浪费,因为每次都必须迭代整个文章数组。更好的方法是组织文章数组,使数组键为文章ID。如...

当装载物品,做这样的事情:

$articles = array(); 
$articlesResultSet; // Imagine this is an array of results that have just been fetched from the database. 
foreach ($articlesResultSet as $a) { 
    $articles[$a['ArticleId']] = $a; 
} 

你就必须$articles其中数组关键是文章ID。这使得getArticle函数如下...

function getArticle($articleIdToFind, $articles) { 
    $result = null; 
    if (array_key_exists($articleIdToFind, $articles)) { 
     $result = $articles[$articleIdToFind]; 
    } 
    return $result; 
}