1
Good afternoon! Although I have researched the subject and searched in the documentation, I have not yet been able to come up with a solution to the following problem.. I have an array brought from the bank with titles and items.
The array comes to me as follows:
$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 transform this array into a new one, with the items already relocated, example:
$limpo[0] = [
"titulo" => "titulo1",
"item" => "item 1",
];
$limpo[1] = [
"titulo" => "titulo 2",
"item" => "item 2",
"item" => "item 3,
];
That is, the titles will not repeat themselves.
So far, I’ve assembled 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, the moment you fall in ($value["titulo"] == $comparacao)
, the "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",
];
Is there any way to push in the previous position? The snippet with commented push is returning an error by indicating the previous position..
Hugs.
You cannot have two keys with the same name on the same level.
– Roberto de Campos