here I have a function to create a category. I need to select all subcategories and create a json code with them, and in it organized categories according to their subid
function unflattenArray($flatArray){
$refs = array();
$result = array();
while(count($flatArray) > 0){
for ($i=count($flatArray)-1; $i>=0; $i--){
if ($flatArray[$i]["parent"]==0){
$result[$flatArray[$i]["id"]] = $flatArray[$i];
$refs = &$result[$flatArray[$i]["id"]];
unset($flatArray[$i]);
$flatArray = array_values($flatArray);
}
else if ($flatArray[$i]["parent"] != 0){
if (array_key_exists($flatArray[$i]["parent"], $refs)){
$o = $flatArray[$i];
$refs[$flatArray[$i]["id"]] = $o;
$refs[$flatArray[$i]["parent"]]["subs"][] = &$refs[$flatArray[$i]["id"]];
unset($flatArray[$i]);
$flatArray = array_values($flatArray);
}
}
}
}
return $result;
}
this chooses this
{
"17": {
"id": 17,
"parent": 0,
"title": "XXX3"
},
"41": {
"id": 41,
"parent": 0,
"title": "XXX2",
"subs": [
{
"id": 45,
"parent": 41,
"title": "XXX7",
"subs": [
{
"id": 102,
"parent": 45,
"title": "XXX10"
},
{
"id": 101,
"parent": 45,
"title": "XXX9"
}
]
}
]
},
"85": {
"id": 85,
"parent": 0,
"title": "XXX2"
},
"1": {
"id": 1,
"parent": 0,
"title": "XXX1",
"subs": [
{
"id": 65,
"parent": 1,
"title": "XXX6"
}
]
}
}
and I would need to select the same json, but without header !
{
"17": { // <--- remove this ( "17": )
"id": 17,
"parent": 0,
"title": "XXX3"
},
"41": {
"id": 41,
"parent": 0,
"title": "XXX2",
"subs": [
{
.....
I can’t delete the "id" line from the header, I only need a line with information
2
Answers
Change
to
so it just appends to an indexed array instead of creating an associative array.
why no apply array_values to $result var before return it?