-1

How can I combine the text values of the same pr value?

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)
)

Output:

$newarray = array(
        "project1" => "text1 | text2 | text5",
        "project2" => "text3 | text4",
    );
Cœur
  • 37,241
  • 25
  • 195
  • 267
M1NT
  • 386
  • 1
  • 4
  • 13

3 Answers3

2

Just loop your array and create new array.

$newArray = [];

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

}
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • Throws an error (don't get it %)P http://sandbox.onlinephpfunctions.com/code/57920134e116c3fb40a2ca562e624f34a8d39a85. – loveNoHate Sep 16 '14 at 11:23
  • @DOCASAREL Just few typos. http://sandbox.onlinephpfunctions.com/code/1de62d53757bf5a726bf868d29f95744b26cb205 – Justinas Sep 16 '14 at 11:26
2

I would do it this way:

<?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);

Output:

array(2) { ["project1"]=> string(21) "text1 | text2 | text5" ["project2"]=> string(13) "text3 | text4" }

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
1

This also makes sure that a certain text is added only once per project.

$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);
}

There are of course shorter solutions that use more advanced array functions, but this one is easier to understand. Note: the code is untested.

Mate Solymosi
  • 5,699
  • 23
  • 30