Dan February 2016

Getting information out of a multidimensional array for 1 specific item

I have an array with this structure :

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)

Now I want to use the ArticleId to get all te product informations of that article. I figured that I first need to find the proper key number with the article and then get the information out of that key, but I can't figure out how to do it.

Answers


RiggsFolly February 2016

You can use a foreach loop to process over the whole array and then pick out each ArticleId

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

    // do something with the ArticleId
}


Tom Wright February 2016

The way with the current code would be to do something like this...

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

This seems a little wasteful though as you will have to iterate over the entire articles array every time. A better way would be to organize the article array so the array key is the article id. Eg...

When loading the articles, do something like this:

$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;
}

You then have $articles where the array key is the article id. That turns the getArticle function to the following....

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

Post Status

Asked in February 2016
Viewed 2,936 times
Voted 9
Answered 2 times

Search




Leave an answer