合并数组值和array_walk_recursive

问题描述 投票:0回答:2

标题很糟糕,但不幸的是我想不出更好的东西来描述我的情况。

假设以下代码,然后我将解释我想要的内容。

$invalid_id = array('100', '110', '120');
$invalid_status = array('200', '210');
$already_exported = array('400', '450');

$tmp = array(
    'There is no order with that ID' => $invalid_id,
    'The order has an invalis status' => $invalid_status,
    'The order was previously exported' => $already_exported,
);

echo '<div><p>' . sprintf('No orders were exported (%s).', implode(', ', array_merge($invalid_id, $invalid_status, $already_exported))) . '</p></div>';

所以上面的代码会产生这样的输出:

<div><p>No orders were exported (100, 110, 120, 200, 210, 400, 450).</p></div>

问题是我想添加每个订单 ID 被拒绝的原因。所以我使用了

$tmp
数组,键是每个数组的值(订单 ID)被拒绝的原因。因此,该键应该在
<span title="the reason - appropriate key of the $tmp array - goes here">each id</span>
场景中使用,以便在用户将鼠标悬停在每个被拒绝的 ID 上时显示原因。

我可以轻松构建一个函数来实现我想要的功能,但我确信也有一种优雅的、超短的方法来实现它。它涉及到

array_walk_recursive()
,但我还无法理解它,所以我请求你们的帮助!

php array-merge array-walk
2个回答
0
投票

您可以在使用

array_diff
检查元素被拒绝后使用
array_merge


0
投票

因为您需要访问第一级键和第二级值,所以不必费心寻求一些时尚的函数式迭代;使用 implode 会产生一些混乱的代码。使用直接的嵌套循环并没有什么可耻的。

代码:(演示

foreach ($tmp as $reason => $ids) {
    foreach ($ids as $id) {
        printf('<p title="%s">Error on %d</p>' . "\n", $reason, $id);
    }
}

输出:

<p title="There is no order with that ID">Error on 100</p>
<p title="There is no order with that ID">Error on 110</p>
<p title="There is no order with that ID">Error on 120</p>
<p title="The order has an invalid status">Error on 200</p>
<p title="The order has an invalid status">Error on 210</p>
<p title="The order was previously exported">Error on 400</p>
<p title="The order was previously exported">Error on 450</p>
© www.soinside.com 2019 - 2024. All rights reserved.