如何有效地从数组中获取特定值?

时间:2022-12-21 11:08:41

I have an array like this

我有一个这样的数组

array(3) {
  [0]=>
  array(2) {
    ["company"]=>
    string(15) "Company A"
    ["value"]=>
    string(6) "100"
  }
  [1]=>
  array(2) {
    ["company"]=>
    string(9) "Company B"
    ["value"]=>
    string(6) "150"
  }
  [2]=>
  array(2) {
    ["company"]=>
    string(13) "Company C"
    ["value"]=>
    string(6) "200"
  }
}

Now I want to get all company names and concatenate them by commata. I can go like this:

现在我想要获取所有的公司名称并通过逗号连接它们。我可以这样说:

foreach ($array as $a) {
    $companies[] = $a['company'];
}
$company_names = implode(',', $companies);
var_dump($company_names);

Prints

打印

string(29) "Company A,Company B,Company C"

So to say: It works. But this seems inefficient to me, that thing with the loop.

所以说:它是有效的。但在我看来,这个循环是无效的。

Are there more efficient ways to come to the same result? E.g. using array_keys or stuff?

有没有更有效的方法来达到同样的结果?例如使用array_keys或其他东西?

3 个解决方案

#1


4  

You can use array_column() but it requires PHP version greater than 5.5:

可以使用array_column(),但它要求PHP版本大于5.5:

$array = array_column($companies, 'company');
echo implode(',', $array);

#2


1  

Use array_column() as suggested by Fu Xu:

按照Fu Xu的建议使用array_column():

$array = array_column($companies, 'company');
echo implode(',', $array);

Demo!

演示!

#3


1  

Are there more efficient ways to come to the same result?

有没有更有效的方法来达到同样的结果?

Efficient is a broad term. I'll assume efficient to mean native. In which case, yes, in PHP 5.5+ you can use array_column() as answered by Fu Xu.

高效是一个广义的术语。我假设效率是指本地的。在这种情况下,是的,可以在PHP 5.5+中使用array_column()作为Fu Xu的答案。

Otherwise, in PHP < 5.5, no. That is there is nothing native. While you could combine any of the dozens of native PHP array functions to achieve the same thing, they're simply more ways to skin a cat.

否则,在PHP < 5.5,不。那就是没有什么是本土的。虽然您可以组合几十个本地PHP数组函数来实现相同的功能,但它们只是为cat提供更多的方法。

#1


4  

You can use array_column() but it requires PHP version greater than 5.5:

可以使用array_column(),但它要求PHP版本大于5.5:

$array = array_column($companies, 'company');
echo implode(',', $array);

#2


1  

Use array_column() as suggested by Fu Xu:

按照Fu Xu的建议使用array_column():

$array = array_column($companies, 'company');
echo implode(',', $array);

Demo!

演示!

#3


1  

Are there more efficient ways to come to the same result?

有没有更有效的方法来达到同样的结果?

Efficient is a broad term. I'll assume efficient to mean native. In which case, yes, in PHP 5.5+ you can use array_column() as answered by Fu Xu.

高效是一个广义的术语。我假设效率是指本地的。在这种情况下,是的,可以在PHP 5.5+中使用array_column()作为Fu Xu的答案。

Otherwise, in PHP < 5.5, no. That is there is nothing native. While you could combine any of the dozens of native PHP array functions to achieve the same thing, they're simply more ways to skin a cat.

否则,在PHP < 5.5,不。那就是没有什么是本土的。虽然您可以组合几十个本地PHP数组函数来实现相同的功能,但它们只是为cat提供更多的方法。