I have a script that goes through a CSV file and puts each row as an array into another array (nested array?). Each row has 2-3 fields for the category of the item in that row. I’m trying to work through how to create a multidimensional array out of these categories. Here is the source I currently have:
$csv = new File_CSV_DataSource;
if ($csv->load($file)) {
$items = $csv->getHeaders();
$csv->getColumn($items[2]);
if ($csv->isSymmetric()) {
$items = $csv->connect();
} else {
$items = $csv->getAsymmetricRows();
}
$items = $csv->getrawArray();
}
$mainCats = array();
$subCats = array();
$subSubs = array();
foreach($items as $item){
if(!in_array($item[10], $mainCats)){
$mainCats[] = $item[10];
}
}
foreach($items as $item){
if(!array_key_exists($item[11], $subCats)){
$parent = array_search($item[10], $mainCats);
$subCats[$item[11]] = $parent;
}
}
foreach($items as $item){
if(!array_key_exists($item[12], $subSubs)){
$parent = array_search($item[11], array_keys($subCats));
$subSubs[$item[12]] = $parent;
}
}
What this does so far is create 3 arrays with the format of:
$mainCats = Array(
[0] => Main Cat 1,
[1] => Main Cat 2,
[2] => Main Cat 3
);
$subCats = Array(
[Sub Cat 1] => 0,
[Sub Cat 2] => 1,
[Sub Cat 3] => 2
);
$subSubs = Array(
[Sub Sub 1] => 0,
[Sub Sub 2] => 1,
[Sub Sub 3] => 2
);
The numeric values of each of the last 2 arrays are the index of their parent category in the previous array. What I would like to do is to merge them all into one large array in the format of:
$cats = Array(
[0] => Array(
'name' => Main Cat 1,
'subs' => Array(
[0] => Array(
'name' => Sub Cat 1,
'subs' => Array(
'name' => Sub Sub 1
)
)
)
),
[1] => Array(
'name' => Main Cat 2,
'subs' => Array(
[0] => Array(
'name' => Sub Cat 2,
'subs' => Array(
'name' => Sub Sub 2
)
)
)
),
[2] => Array(
'name' => Main Cat 3,
'subs' => Array(
[0] => Array(
'name' => Sub Cat 3,
'subs' => Array(
'name' => Sub Sub 3
)
)
)
),
);
I know there has to be a far more efficient way of doing this, but I can’t figure it out.
EDIT – I should also mention that not all rows have a 3rd category field value.
I prefer to index them by name: