gpt4 book ai didi

php - 在php中加入两个数组

转载 作者:行者123 更新时间:2023-12-01 23:46:28 25 4
gpt4 key购买 nike

我有两个数组,第一个数组名称是 $balances,输出如下:

Array
(
[0] => Array
(
[index] => 0
[account_id] => 1
[company_id] => 6
[company_code] => ABBANK
)

[1] => Array
(
[index] => 6
[account_id] => 1
[company_id] => 147
[company_code] => IFIC
)

[2] => Array
(
[index] => 11
[account_id] => 1
[company_id] => 293
[company_code] => SOUTHEASTB
)
)

第二个数组名称是 $market,它的输出是:

Array
(
[0] => Array
(
[company] => SOUTHEASTB
[high] => 0
[low] => 0

)

[1] => Array
(
[company] => IFIC
[high] => 0
[low] => 0

)

[2] => Array
(
[company] => ABBANK
[high] => 0
[low] => 0
)
)

我合并这两个数组并得到以下输出。第二个数组使用下面的代码将数组值推送到第一个数组,产生的结果不符合我的要求:

$result = array();
foreach ($balances as $key => $value) {
$result[] = array_merge($value, $market[$key]);
}

输出:

Array
(
[0] => Array
(
[index] => 0
[company_code] => ABBANK
[company] => 1JANATAMF
[high] => 5.3
[low] => 5
)

[1] => Array
(
[index] => 6
[company_code] => IFIC
[company] => 1STPRIMFMF
[high] => 16.9
[low] => 16.2
)

[2] => Array
(
[index] => 11
[company_code] => SOUTHEASTB
[company] => AAMRANET
[high] => 44
[low] => 43
)
)

我的挑战是检查 $balances[company_code] == $market['company'] 并将第二个数组附加到第一个数组,这将产生以下结果。

Array
(
[0] => Array
(
[index] => 0
[account_id] => 1
[company_id] => 6
[company_code] => ABBANK
[high] => 0
[low] => 0
)

[1] => Array
(
[index] => 6
[account_id] => 1
[company_id] => 147
[company_code] => IFIC
[high] => 0
[low] => 0
)

[2] => Array
(
[index] => 11
[account_id] => 1
[company_id] => 293
[company_code] => SOUTHEASTB
[high] => 0
[low] => 0
)
)

但是上面的代码块不能满足我的需求。因为此代码块仅使用合并功能将第二个数组推送到第一个数组。我尝试了我库存中的所有其他解决方案。有没有人可以给我任何解决方案,将不胜感激。

最佳答案

这可以通过使用 array_column 以最少的代码解决。要按公司名称重新索引两个数组,然后可以使用 array_merge_recursive 合并这两个数组:

$output = array_merge_recursive(array_column($balances, null, 'company_code'), 
array_column($market, null, 'company'));

输出:

Array
(
[ABBANK] => Array
(
[index] => 0
[account_id] => 1
[company_id] => 6
[company_code] => ABBANK
[company] => ABBANK
[high] => 0
[low] => 0
)
[IFIC] => Array
(
[index] => 6
[account_id] => 1
[company_id] => 147
[company_code] => IFIC
[company] => IFIC
[high] => 0
[low] => 0
)
[SOUTHEASTB] => Array
(
[index] => 11
[account_id] => 1
[company_id] => 293
[company_code] => SOUTHEASTB
[company] => SOUTHEASTB
[high] => 0
[low] => 0
)
)

如果你想要一个数字索引的结果,只需将 $output 传递给 array_values .

$output = array_values($output);

Demo on 3v4l.org

关于php - 在php中加入两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64096578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com