dtgvl48608
dtgvl48608
2014-03-22 16:45

如何从数组中获取特定数据?

已采纳

Right now I have a problem with retrieving data form arrays, maybe it's really simple (probably it is) but I am struggling wiht it since morning and it appears, that my knowledge about PHP is worth nothing...so I have few arrays:

array( "name" => "Array 1",
    "type" => "array"),

array( "name" => "Array 2",
    "type" => "whatever"),

array( "name" => "Array 3",
    "type" => "whatever"),

array( "name" => "Array 4",
    "type" => "array"),

array( "name" => "Array 5",
    "type" => "whatever"),

What I need to do is to display 'name' of arrays of the 'array' type, I know I need a foreach loop but how to construct 'foreach ($arrays as $array) {' to get the desired result?

EDIT

Thanks for all the replies, but I tihnk I didn't make myself clear. I need to display "name" only when there is a "type" => "array" present within array, every other arrays' "name" should be omitted.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doukanxi4246 doukanxi4246 7年前

    You'll need to do something like this:

    foreach($arrays as $array) {
        if($array['type'] == 'array') {
            print($array['name']);
        }
    }
    
    点赞 评论 复制链接分享
  • dongshun5963 dongshun5963 7年前

    put the arrays into a "container" array first, then you can use that one...

    <?php
    
    $data = array(
    
        array( "name" => "Array 1",
            "type" => "array"),
    
        array( "name" => "Array 2",
            "type" => "whatever"),
    
        array( "name" => "Array 3",
            "type" => "whatever"),
    
        array( "name" => "Array 4",
            "type" => "array"),
    
        array( "name" => "Array 5",
            "type" => "whatever")
    );
    
    foreach($data as $array) {
        if($array['type'] == 'array') {
          print($array['name']);
        }
    }
    
    点赞 评论 复制链接分享
  • doubingjian2006 doubingjian2006 7年前

    An array_map will do

    array_map(function ($v){ if($v['type']=="array"){echo $v['name']."<br>";}},$arr);
    

    OUTPUT :

    Array 1
    Array 4
    

    Demo

    点赞 评论 复制链接分享

相关推荐