search

Home  >  Q&A  >  body text

php - Interview question: Article list and category list (both two-dimensional), if the category corresponding to the article is taken out through a loop

P.S.: They are all two-dimensional arrays (numeric index)

I also want to ask: Where is the inspection point? The context of the Lenovo interview was maybe a function test?

迷茫迷茫2718 days ago701

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-06-20 10:09:33

    I guess it’s the array_column function.

    # 数据准备
    $articles = [
        ['id' => 1, 'name' => '文章1', 'category_id' => 3],
        ['id' => 2, 'name' => '文章2', 'category_id' => 5],
        ['id' => 3, 'name' => '文章3', 'category_id' => 6]
    ];
    $categories = [
        ['id' => 1, 'name' => '分类1'],
        ['id' => 2, 'name' => '分类2'],
        ['id' => 3, 'name' => '分类3'],
        ['id' => 4, 'name' => '分类4'],
        ['id' => 5, 'name' => '分类5'],
        ['id' => 6, 'name' => '分类6']
    ];
    
    $categories = array_column($categories, NULL, 'id');
    # 经过上面这步之后,新的$categories值如下:
    # [
    #     '1' => ['id' => 1, 'name' => '分类1'],
    #     '2' => ['id' => 2, 'name' => '分类2'],
    #     '3' => ['id' => 3, 'name' => '分类3'],
    #     '4' => ['id' => 4, 'name' => '分类4'],
    #     '5' => ['id' => 5, 'name' => '分类5'],
    #     '6' => ['id' => 6, 'name' => '分类6']
    # ];
    # array_column函数将一个二维矩阵型的数组中的列拆出来,输出一维数组。
    # 这个函数有三个参数,第一个参数为源数组
    # 第二个参数为取出来当键值的列名,比如这个例子中对$categories可以取'id'或者'name',当然也可以用NULL,表示将整个值(此处为['id' => 1, 'name' => '分类1']之类)原封不动作为新的值
    # 第三个参数为取出来当键名的列,可选。如果不给或者为NULL,则自动编号。
    #
    # 上面做的这个array_column操作,是让之后遍历文章时,可以通过里面的category_id列的值直接找到对应的$categories里面的值。
    
    foreach($articles as &$article) {
        $cat_id = $article['category_id']; // 这步可以嵌入下面的代码,是为了看起来没那么多嵌套而已
        $article['category'] = $categories[$cat_id];
    }
    
    # 新的$articles:
    # [
    #     ['id' => 1, 'name' => '文章1', 'category_id' => 3, 'category' => ['id' => 3, 'name' => '分类3']],
    #     ['id' => 2, 'name' => '文章2', 'category_id' => 5, 'category' => ['id' => 5, 'name' => '分类5']],
    #     ['id' => 3, 'name' => '文章3', 'category_id' => 6, 'category' => ['id' => 6, 'name' => '分类6']]
    # ];

    reply
    0
  • Cancelreply