-1

如何组合相同 pr 值的文本值?

Array ( 
[0] => Array ( [ID] => 1 [text] => text1 [pr] => project1) 
[1] => Array ( [ID] => 2 [text] => text2 [pr] => project1)
[2] => Array ( [ID] => 2 [text] => text3 [pr] => project2)
[3] => Array ( [ID] => 2 [text] => text4 [pr] => project2)
[4] => Array ( [ID] => 2 [text] => text5 [pr] => project1)
)

输出:

$newarray = array(
        "project1" => "text1 | text2 | text5",
        "project2" => "text3 | text4",
    );
4

3 回答 3

2

我会这样做:

<?php

$array = Array(
    0 => Array('ID' => 1, 'text' => 'text1', 'pr' => 'project1'),
    1 => Array('ID' => 2, 'text' => 'text2', 'pr' => 'project1'),
    2 => Array('ID' => 2, 'text' => 'text3', 'pr' => 'project2'),
    3 => Array('ID' => 2, 'text' => 'text4', 'pr' => 'project2'),
    4 => Array('ID' => 2, 'text' => 'text5', 'pr' => 'project1'),
);


$newArray = [];

foreach ($array as $item) {
    $newArray[$item['pr']][] = $item['text'];
}

foreach ($newArray as $k => $v) {
    $newArray[$k] = implode(' | ', $v);
}


var_dump($newArray);

输出:

数组(2) { ["project1"]=> 字符串(21) "text1 | text2 | text5" ["project2"]=> 字符串(13) "text3 | text4" }

于 2014-09-16T11:14:00.933 回答
2

只需循环您的数组并创建新数组。

$newArray = [];

foreach ($myArray as $elements) {
    if (isset($newArray[$elements['pr']])) {
        $newArray[$elements['pr']] .= " | {$elements['text']}";
    } else {
        $newArray[$elements['pr']] = $elements['text'];
    }

}
于 2014-09-16T11:08:18.587 回答
1

这也确保每个项目仅添加一次特定文本。

$newarray = array();

// Loop through the old array, set the current row to the $row variable
foreach($oldarray as $row)
{
  // If the project doesn't yet exist in the new array, we create an empty array for it
  if(!array_key_exists($row["pr"], $newarray))
  {
    $newarray[$row["pr"]] = array();
  }

  // We add the current text to the array of the project, but only if it is not already there
  if(!in_array($row["text"], $newarray[$row["pr"]]))
  {
    $newarray[$row["pr"]][] = $row["text"];
  }
}

// Loop through the new array, and stich the texts within the project-array together with the separator `|`
foreach($newarray as $k => $v)
{
  $newarray[$k] = implode(" | ", $v);
}

当然还有更短的解决方案使用更高级的数组函数,但这个更容易理解。注意:代码未经测试。

于 2014-09-16T11:11:06.023 回答