简体   繁体   English

来自一个变量的不同数组的相同值

[英]Same values from different arrays in one variable

I have a question, because I can't figure it out and I can't find it anywhere (maybe the wrong search-words I don't know..). 我有一个问题,因为我无法弄清楚,也无法在任何地方找到它(也许是我不知道的错误搜索词。)。 I have the following: 我有以下几点:

Array
(
    [0] => Array
        (
            [Factuurnummer] => 50
            [Omschrijving] => Thing 1
        )

    [1] => Array
        (
            [Factuurnummer] => 50
            [Omschrijving] => Thing 2
        )

    [2] => Array
        (
            [Factuurnummer] => 51
            [Omschrijving] => Thing 2
        )

    [3] => Array
        (
            [Factuurnummer] => 51
            [Omschrijving] => Thing 3
        )

    [4] => Array
        (
            [Factuurnummer] => 51
            [Omschrijving] => Thing 4
        )

)

Now when I use a foreach to print it all in a table I get 5 rows, but I only want 2, based on the same 'Factuurnummer'. 现在,当我使用foreach将其全部打印到表中时,基于相同的“ Factuurnummer”,我得到了5行,但我只想要2行。 So 1 row with 'Factuurnummer'=50 and 'Omschrijving'=Thing 1, Thing 2 and another row with 'Factuurnummer'=51 and 'Omschrijving'=Thing 2, Thing 3, Thing 4. 因此,“ Factuurnummer” = 50且“ Omschrijving” = Thing 1,Thing 2的第一行和“ Factuurnummer” = 51且“ Omschrijving” = Thing 2,Thing 3,Thing 4的另一行。

I've read something about array_intersect, but I don't know if that will help in this case. 我已经阅读了有关array_intersect的内容,但是我不知道在这种情况下是否有帮助。 The nicest would be if the value from 'Omschrijving' based on same 'Factuurnummer' would be separated with a comma (like my little example). 最好的情况是,如果基于相同“ Factuurnummer”的“ Omschrijving”中的值将用逗号分隔(例如我的小示例)。

Hope I was clear enough and someone could help me in the right direction! 希望我足够清楚,有人可以在正确的方向帮助我!

You should rewrite your array before you print it, assuming above array is called $data: 假设上面的数组称为$ data,则应在打印数组之前重写它:

$facturen = array();
foreach($data as $row) {
    $factuurnummer = $row['Factuurnummer'];
    if (!isset($facturen[$factuurnummer])) {
        $facturen[$factuurnummer] = array();
    }
    $facturen[$factuurnummer][] = $row['Omschrijving'];
}

// On display:
foreach($facturen as $factuurnummer => $omschrijvingen) {
     echo $factuurnummer.': '.implode(', ', $omschrijvingen);
}

You can easily use array_walk() to write your data into an array with more usable format: 您可以轻松地使用array_walk()将数据写入具有更多可用格式的数组中:

$new_array = array();
array_walk($existing_array, function($item, $key_not_used) use ($new_array) {
    $new_array[$item['Factuurnummer']][] = $item['Omschrijving'];
});
var_dump($new_array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM