获取一串句点分隔的属性并将其转换为 php 中的 json 对象
我相当确定我在这里遗漏了一些非常明显的东西,但它就在这里。
我正在更新一个应用程序中的搜索功能,该应用程序正在运行循环并执行大量 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的函数是迈克的一部分,尽管它有一个问题,即顶级值在数组的每次传递中不断重置,因此只有最后一个句点分隔的属性才进入。
请参阅更新版本。
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.
我确信有更优雅的东西,但又快速又肮脏:
I am sure there is something more elegant, but quick and dirty:
输出:
Outputs: