我相当肯定我在这里失去了一些非常明显的东西,但是在这里。
我正在更新正在运行循环的应用程序中的搜索功能,并执行大量的sql查询以将对象/表关系转换为返回所有内容的大型查询。 然而,我认为返回关系的唯一途径是分段的,我现在想要做的是将键和值的平面数组转换为关联数组,然后用json_encode进行json化。
例如,我拥有的是...
array( "ID"=>10, "CompanyName"=>"Some Company", "CompanyStatusID"=>2, "CompanyStatus.Status"=>"Active", "addressID"=>134, "address.postcode"=>"XXX XXXX", "address.street"=>"Some Street" );而我想把它变成这个......
array( "ID"=>10, "CompanyName"=>"Some Company", "CompanyStatusID"=>2, "CompanyStatus"=>array( "Status"=>"Active" ), "addressID"=>134, "address"=>array( "postcode"=>"XXX XXXX", "street"=>"Some Street" ) );现在我确信这应该是一个相当简单的递归循环,但今天早上我终身无法弄清楚。
任何帮助是极大的赞赏。
问候
格雷厄姆。
I'm fairly sure I'm missing something blindingly obvious here but here it goes.
I am working on updating a search function in an application which was running a loop and doing a very large number of sql queries to get object / table relations to one large query that returns everything. However the only way I could think to return relations was period separated, what I am now wanting to do is take the flat array of keys and values and convert it into an associative array to then be jsonified with json_encode.
For example what I have is this...
array( "ID"=>10, "CompanyName"=>"Some Company", "CompanyStatusID"=>2, "CompanyStatus.Status"=>"Active", "addressID"=>134, "address.postcode"=>"XXX XXXX", "address.street"=>"Some Street" );And what I want to turn it into is this...
array( "ID"=>10, "CompanyName"=>"Some Company", "CompanyStatusID"=>2, "CompanyStatus"=>array( "Status"=>"Active" ), "addressID"=>134, "address"=>array( "postcode"=>"XXX XXXX", "street"=>"Some Street" ) );Now I'm sure this should be a fairly simple recursive loop but for the life of me this morning I can't figure it out.
Any help is greatly appreciated.
Regards
Graham.
最满意答案
你的函数是mike的一部分,尽管它存在的问题是顶层值在数组的每次传递过程中都保持复位状态,所以只有最后一个分隔的属性才会使它复位。
请参阅更新的版本。
function parse_array($src) { $dst = array(); foreach($src as $key => $val) { $parts = explode(".", $key); if(count($parts) > 1) { $index = &$dst; $i = 0; $count = count($parts)-1; foreach(array_slice($parts,0) as $part) { if($i == $count) { $index[$part] = $val; } else { if(!isset($index[$part])){ $index[$part] = array(); } } $index = &$index[$part]; $i++; } } else { $dst[$parts[0]] = $val; } } return $dst; }Your function was part way there mike, though it had the problem that the top level value kept getting reset on each pass of the array so only the last period separated property made it in.
Please see updated version.
function parse_array($src) { $dst = array(); foreach($src as $key => $val) { $parts = explode(".", $key); if(count($parts) > 1) { $index = &$dst; $i = 0; $count = count($parts)-1; foreach(array_slice($parts,0) as $part) { if($i == $count) { $index[$part] = $val; } else { if(!isset($index[$part])){ $index[$part] = array(); } } $index = &$index[$part]; $i++; } } else { $dst[$parts[0]] = $val; } } return $dst; }更多推荐
发布评论