gpt4 book ai didi

php - 在php中组合多维数组

转载 作者:行者123 更新时间:2023-12-02 06:31:46 26 4
gpt4 key购买 nike

我在尝试什么

我有 2 个数组,如下所示:

数组 1:

Array
(
[38] => Array
(
[0] => Array
(
[code] => ACC
[amount] => 50
[emp_number] => 38
)

[1] => Array
(
[code] => CAR
[amount] => 60
[emp_number] => 38
)

)

[22] => Array
(
[0] => Array
(
[code] => ACC
[amount] => 110
[emp_number] => 22
)

[1] => Array
(
[code] => AIR
[amount] => 260
[emp_number] => 22
)

[2] => Array
(
[code] => CAP
[amount] => 205
[emp_number] => 22
)
)

)

数组 2:

 Array
(
[0] => Array
(
[code] => ACC
)

[1] => Array
(
[code] => AIR
)

[2] => Array
(
[code] => ARC
)

[3] => Array
(
[code] => ATV
)

[4] => Array
(
[code] => CAP
)

[5] => Array
(
[code] => CAR
)

)

我想要什么

最终数组:

   Array
(
[38] => Array
(
[0] => Array
(
[code] => ACC
[amount] => 50
[emp_number] => 38
)

[1] => Array
(
[code] => AIR
[amount] => ''
[emp_number] => 38
)
[2] => Array
(
[code] => ARC
[amount] => ''
[emp_number] => 38
)

[3] => Array
(
[code] => ATV
[amount] => ''
[emp_number] => 38
)

[4] => Array
(
[code] => CAP
[amount] => ''
[emp_number] => 38
)

[5] => Array
(
[code] => CAR
[amount] => 60
[emp_number] => 38
)

)

[22] => Array
(
[0] => Array
(
[code] => ACC
[amount] => 110
[emp_number] => 22
)

[1] => Array
(
[code] => AIR
[amount] => 260
[emp_number] => 22
)
[2] => Array
(
[code] => ARC
[amount] => ''
[emp_number] => 22
)

[3] => Array
(
[code] => ATV
[amount] => ''
[emp_number] => 22
)

[4] => Array
(
[code] => CAP
[amount] => 205
[emp_number] => 22
)

[5] => Array
(
[code] => CAR
[amount] => ''
[emp_number] => 22
)
)

)

代码

 $count = count($category);
$exp = array();
foreach ($expItem as $empItem) {
$j = 0;
foreach ($category as $cat) {
foreach ($empItem as $emp) {
for ($k = 0; $k < $count; $k++) {
if ($emp['code'] == $category['code']) {
$expItem[$emp['emp_number']][$k]['name'] = $category[$k]['name'];
} else {
$expItem[$emp['emp_number']][$k]['code'] = $category[$k]['code'];
$expItem[$emp['emp_number']][$k]['name'] = $category[$k]['name'];
}
}
}
$j++;
}
}

此处 $expItem 是第一个数组,$category 是第二个数组,我在 $expItem 本身中获取最终数组。 $emp['emp_number'] 是第一个数组“38”和“22”的单元键。它与 codeamount 一起在第一个数组中可用。 $category 还包含值 name

如何组合这两个数组才能正确得到最终数组?

编辑: 第一个数组中的代码与第二个数组中的代码相同。第二个数组包含所有代码和各自的名称。第一个数组显示员工数据,其中显示员工使用的代码数量。我想要的是,如果员工没有使用任何代码,那么第一个数组应该在员工数据中显示相应的代码和金额为 0。代码是动态实现的,因此不能对其进行硬编码。

最佳答案

你能试试这个吗? $result 将具有预期的数组。

$result = [];

foreach($expItem as $key => $item) {

$result[$key] = array_map(function($value) use ($key, $item){
$value['amount'] = '';
$value['emp_number'] = $key;

foreach($item as $_key => $_item) {
if($_item['code'] === $value['code']) {
$value['amount'] = $_item['amount'];
}
}

return $value;

}, $category);

}

关于php - 在php中组合多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33934450/

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