多维数组按对象推送无法正常工作
multidimensional array push an objectwise not working properly
我有一个需要以特定方式格式化的数组,但它正在为其中一个对象生成一个随机密钥。请参阅下面的代码
$temp = [
[
"UID" => "100",
"UPID" => "001",
"PID" => "test1"
],
[
"UID" => "1001",
"UPID" => "002",
"PID" => "test1"
]
];
$child = [];
foreach ($temp as $key => $value) {
$child[$value['UID']][$key]['UPID'] = $value['UPID'];
$child[$value['UID']][$key]['PID'] = $value['PID'];
}
$oldParentData['childUserProductDetail'] = $child;
echo "<pre>";
$result = json_encode($oldParentData, true);
print_r($result);
my expected output
{
"childUserProductDetail": {
"100": [
{
"UPID": "001",
"PID": "test1"
}
],
"1001": [
{
"UPID": "002",
"PID": "test1"
}
]
}
}
getting output
{
"childUserProductDetail": {
"100": [
{
"UPID": "001",
"PID": "test1"
}
],
"1001": {
"1": { // See 1 as key here, that is unwanted
"UPID": "002",
"PID": "test1"
}
}
}
}
这里我不知道第二次数组没有创建并且 1
来自 where.kindly 任何人都根据我的预期答案更新我的代码。
只是零钱。删除正在创建索引的 [Key]
部分,例如 0、1。
所以即使对于 UID = 1001
这是第一条记录,但由于循环键位于 1,我们需要将其删除。
foreach ($temp as $key => $value) {
$child[$value['UID']][] = ['UPID' => $value['UPID'], 'PID'=> $value['PID']];
}
我有一个需要以特定方式格式化的数组,但它正在为其中一个对象生成一个随机密钥。请参阅下面的代码
$temp = [
[
"UID" => "100",
"UPID" => "001",
"PID" => "test1"
],
[
"UID" => "1001",
"UPID" => "002",
"PID" => "test1"
]
];
$child = [];
foreach ($temp as $key => $value) {
$child[$value['UID']][$key]['UPID'] = $value['UPID'];
$child[$value['UID']][$key]['PID'] = $value['PID'];
}
$oldParentData['childUserProductDetail'] = $child;
echo "<pre>";
$result = json_encode($oldParentData, true);
print_r($result);
my expected output
{
"childUserProductDetail": {
"100": [
{
"UPID": "001",
"PID": "test1"
}
],
"1001": [
{
"UPID": "002",
"PID": "test1"
}
]
}
}
getting output
{
"childUserProductDetail": {
"100": [
{
"UPID": "001",
"PID": "test1"
}
],
"1001": {
"1": { // See 1 as key here, that is unwanted
"UPID": "002",
"PID": "test1"
}
}
}
}
这里我不知道第二次数组没有创建并且 1
来自 where.kindly 任何人都根据我的预期答案更新我的代码。
只是零钱。删除正在创建索引的 [Key]
部分,例如 0、1。
所以即使对于 UID = 1001
这是第一条记录,但由于循环键位于 1,我们需要将其删除。
foreach ($temp as $key => $value) {
$child[$value['UID']][] = ['UPID' => $value['UPID'], 'PID'=> $value['PID']];
}