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

时间:2012-11-24 15:17:09

标签: php

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

这是我输入print_r($ arrayOne)时的输出; 我该怎么做才能获得公司专栏,即Agilent Technologies Inc和Alocoa,Inc。

我试过echo $ arrayOne ['Company']和$ arrayOne [0] ['Company'],但它只输出'Array'。

2 个答案:

答案 0 :(得分:3)

你拥有的是一个带有两个子阵列的外部数组,每个子阵列只有一个值。它的关键是3列的描述,其值是CSV值。如果你有PHP 5.3,使用str_getcsv()来解析它并返回第三列

// 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] . "\n";
  }
}

例如输入:

$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.

答案 1 :(得分:0)

你的数组应该是这样的:

$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