gpt4 book ai didi

javascript - 如何从 PHP 中创建对象内的 JavaScript 数组

转载 作者:行者123 更新时间:2023-12-03 03:50:31 25 4
gpt4 key购买 nike

我需要构建一个 array-within-objects-within-array-within-objects 供 JavaScript 使用。我的数据在 PHP 中,我可以使用数组中的 foreach 循环来组织必要的信息:

$officeWiseEmployees = array();
foreach($employeeList as $employee) :
$officeWiseEmployees[$employee->office_name][$employee->employee_id] = $employee->employee_name;
endforeach;

我的目的是创建数组,然后在必要时使用 (object) 进行类型转换以创建其中的对象。顺便说一句,结果数据是:

array:2 [
"Office 1" => array:2 [
1 => "User 1"
2 => "User 2"
]
"Office 2" => array:2 [
3 => "User 3"
4 => "User 4"
]
]

所需的对象内数组...:

[{
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' } ]
}]

问题是,每当我想继续分配数组索引时,我都会在 foreach 循环中失败。

$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);

}
}

您可以看到,在第 3 行,我做错了,因此我只获取了 text 索引下的最后一个 Office 名称。如果我在 textchildren 上引入另一个索引,那么我将进一步超出我需要的设置。

如何以简单的方式将 PHP 数组转换为 JavaScript array-within-objects-within-array-within-objects?我认为这比我想象的要容易,这就是为什么 developer used this .

最佳答案

正如其他人提到的,json_encode 将确定某物是数组还是对象。

很多复杂性来自于将用户 ID 设置为每个元素的键的方式。

<?php

$employees = [
['id' => 1, 'name' => 'Employee 1', 'office' => 'Office 1'],
['id' => 2, 'name' => 'Employee 2', 'office' => 'Office 1'],
['id' => 3, 'name' => 'Employee 3', 'office' => 'Office 2'],
['id' => 4, 'name' => 'Employee 4', 'office' => 'Office 1'],
['id' => 5, 'name' => 'Employee 5', 'office' => 'Office 2'],
];

$offices = [];
foreach ($employees as $employee) {
$offices[$employee['office']][] = [$employee['id'] => $employee['name']];
}

$officesOutput = [];
foreach ($offices as $name => $officeEmployees) {
$employees = [];
foreach ($officeEmployees as $employeeName) {
$employees[] = [
'value' => key($employeeName),
'text' => current($employeeName)
];
}

$officesOutput[] = [
'text' => $name,
'children' => $employees
];
}


echo json_encode($offices, JSON_PRETTY_PRINT);
echo PHP_EOL;
echo json_encode($officesOutput, JSON_PRETTY_PRINT);

结果:

{
"Office 1": [
{
"1": "Employee 1"
},
{
"2": "Employee 2"
},
{
"4": "Employee 4"
}
],
"Office 2": [
{
"3": "Employee 3"
},
{
"5": "Employee 5"
}
]
}
[
{
"text": "Office 1",
"children": [
{
"value": 1,
"text": "Employee 1"
},
{
"value": 2,
"text": "Employee 2"
},
{
"value": 4,
"text": "Employee 4"
}
]
},
{
"text": "Office 2",
"children": [
{
"value": 3,
"text": "Employee 3"
},
{
"value": 5,
"text": "Employee 5"
}
]
}
]

关于javascript - 如何从 PHP 中创建对象内的 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com