I need to build an array-within-objects-within-array-within-objects for JavaScript uses. My data is in PHP, and I could organize my necessary information using a foreach loop in an array:
$officeWiseEmployees = array();
foreach($employeeList as $employee) :
$officeWiseEmployees[$employee->office_name][$employee->employee_id] = $employee->employee_name;
endforeach;
My intention was to make arrays, then I'll typecast with (object)
where necessary to make the objects within. By the way the resulted data is:
array:2 [
"Office 1" => array:2 [
1 => "User 1"
2 => "User 2"
]
"Office 2" => array:2 [
3 => "User 3"
4 => "User 4"
]
]
The desired array-within-objects...:
[{
text: 'Office Name 1',
children:
[ { value: 1, text: 'Employee 1' }, { value: 2, text: 'Employee 2' } ]
},
{
text: 'Office Name 2',
children:
[ { value: 3, text: 'Employee 3' }, { value: 4, text: 'Employee 4' } ]
}]
Issue is, whenever I wanted to proceed to assign the Array Indexes, I's failing within the foreach loops.
$make_up_array = array();
foreach( $officeWiseEmployees as $office_name => $office_employees ) {
$make_up_array['text'] = $office_name;
foreach( $office_employees as $employee_id => $employee_name ) {
// dump($employee_id);
// dump($employee_name);
}
}
You can see, on line 3 I's doing wrong, so I's getting only the last Office name under text
index. If I introduce another index over text
or children
, then I's getting further beyond the setup I needed.
How can I convert my PHP array into a JavaScript array-within-objects-within-array-within-objects in an easy way? I thought it could be easier than I might think of, that's why developer used this.