dsm42026
dsm42026
2012-11-24 15:17

php从数组中获取特定列的所有值

已采纳
Array ( [0] => Array ( [No.,"Ticker","Company"] => 
                        1,"A","Agilent Technologies Inc." ) 
        [1] => Array ( [No.,"Ticker","Company" ] => 
                        2,"AA","Alcoa, Inc.") 
      )

This is the output when i type print_r($arrayOne); What can I do so I can only get the Company column i.e. Agilent Technologies Inc, and Alocoa, Inc.

I tried echo $arrayOne['Company'] and $arrayOne[0]['Company'] but it just outputted 'Array'.

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

2条回答

  • dragon88112 dragon88112 9年前

    What you have is an outer array with two sub-arrays, each of which has only one value. Its key is the description of the 3 columns, and its value is the CSV value. If you have PHP 5.3, use str_getcsv() to parse it and return the third column

    // Loop over the outer array
    foreach ($arrayOne as  $subarr) {
      // Loop over the sub-arrays (though your sample only has one value each)
      // could also use array_pop()
      foreach ($subarr as $key => $csvstring) {
        // $csvstring holds the CSV value like  '1,"A","Agilent Technologies Inc."'
        // Parse it with str_getcsv()
        $cols = str_getcsv($csvstring);
        // Company name is the 3rd value, key [2]
        echo $cols[2] . "
    ";
      }
    }
    

    For example with the input:

    $arrayOne = array(
      array('No.,"Ticker","Company"' => '1,"A","Agilent Technologies Inc."' ), 
      array('No.,"Ticker","Company"'  => '2,"AA","Alcoa, Inc."') 
    );
    // The above loop prints:
    Agilent Technologies Inc.
    Alcoa, Inc.
    
    点赞 评论 复制链接分享
  • douxuan0698 douxuan0698 9年前

    Your array should be like this:

    $arrayOne = array(array('no' => 1, 'ticker' => 'A', 'company' => 'Agilent Technologies Inc.'),
                      array('no' => 2, 'ticker' => 'AA', 'company' => 'Alcoa Inc.'));
    
    echo $array[0]['company']; // will print Agilent Technologies
    
    点赞 评论 复制链接分享

为你推荐