gpt4 book ai didi

php - 递归函数php

转载 作者:行者123 更新时间:2023-12-04 06:48:07 25 4
gpt4 key购买 nike

我有一个看起来像这样的数组

$dataArray = array (
0 =>
array (
'UserId' => '804023',
'ProjectCode' => 'RA1234',
'Role' => 'PI',
),
1 =>
array (
'UserId' => '804023',
'ProjectCode' => 'RA1234',
'Role' => 'PM',
),
2 =>
array (
'UserId' => '804023',
'ProjectCode' => 'A90123',
'Role' => 'CI',
),
3 =>
array (
'UserId' => '804023',
'ProjectCode' => 'A20022',
'Role' => 'PM',
),
)

我需要它看起来像这样
$expected = array (
804023 =>
array (
'RA1234' =>
array (
0 => 'PI',
1 => 'PM',
),
'A90123' =>
array (
0 => 'PI',
),
'A20022' =>
array (
0 => 'CI',
),
),
)

我认为这可以使用递归来实现,因为这是我可能多次遇到的场景

我已经在形成嵌套数组键的键数组中传递了这么远,即
$keys=array("UserId","projectCode","Role");

但只是没有看到从这里去哪里有任何指示?
public function structureData(array $data, array $keys)
{
//$structuredData = array();


foreach ($data as $key => $value)
{
$keyForData = array_slice($keys,0,1);


$remainingKeys = $keys;
array_shift($remainingKeys);

if (!array_key_exists($value[$keyForData[0]], $structuredData))
{

$count=count($remainingKeys);


$structuredData[$value[$keyForData[0]]] =array();
// this returns as expected array(804023 =>array ()); but subsequent recursive calls with the remaining data fail



}

}
return $structuredData);
}

最佳答案

一个粗糙但有效的解决方案。

function structureData($data, $keys){                                           
$out = array();
foreach($data as $row){
$subout = &$out;
foreach(array_slice($keys, 0, -1) as $key){
$value = $row[$key];
$subout = &$subout[$value];
}
$subout[] = $row[$keys[count($keys) - 1]];

}
return $out;
}

print_r(structureData($dataArray, array('UserId', 'ProjectCode', 'Role')));

关于php - 递归函数php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3504679/

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