Good afternoon! Although I have researched the subject and searched the documentation, I still can not come up with a solution to the following problem .. I have an array brought from the bank with titles and items.
The array looks like this:
$a[0] = [
"titulo" => "titulo1",
"item" => "item 1",
];
$a[1] = [
"titulo" => "titulo 2",
"item" => "item 2",
];
$a[2] = [
"titulo" => "titulo 2",
"item" => "item 3",
];
My goal is to turn this array into a new one, with items already reallocated, eg:
$limpo[0] = [
"titulo" => "titulo1",
"item" => "item 1",
];
$limpo[1] = [
"titulo" => "titulo 2",
"item" => "item 2",
"item" => "item 3,
];
In other words, titles will not be repeated.
So far, I've put the code as follows ..
foreach ($a as $key => $value) {
if($key>0){
$comparacao = ($a[$key-1]["titulo"]);
echo($comparacao."<br>");
}
if($key==0){
$limpo[$key] = [
"titulo" => $value['titulo'],
"item" => $value['item']
];
}else if($value["titulo"] != $comparacao){
$limpo[$key] = [
"titulo" => $value['titulo'],
"item" => $value['item']
];
}
else if($value["titulo"] == $comparacao){
//array_push($limpo[($key-1)]['item'], $value['item']);
$limpo[($key-1)] = [
"titulo" => $value['titulo'],
"item" => $value['item']
];
}
}
However, at the moment it falls in ($value["titulo"] == $comparacao)
, "item 3" is allocated in place of item 2, being as follows:
$limpo[0] = [
"titulo" => "titulo1",
"item" => "item 1",
];
$limpo[1] = [
"titulo" => "titulo 2",
"item" => "item 3",
];
Would you have any way to push in the previous position? The commented push snippet is returning an error because it indicates the previous position.
Hugs.