我有多个单独的对象数组,这些对象是从MySQL导入(JSON编码)的,需要合并和更改结构。我基本上需要组合的[时间]和[天]项是[周期]的数组,以便可以对其进行循环。当前,在导入/解码后,每个MySQL查询的对象结构数组看起来像这样:
(查询1)
stdClass Object
(
[day] => Array
(
[0] => stdClass Object
(
[day] => 1
[time] => 60
[name] => Running
[cycle] => 1
)
[1] => stdClass Object
(
[day] => 5
[time] => 30
[name] => Running
[cycle] => 1
)
)
[id] => 15359593
)
(查询2)
stdClass Object
(
[day] => Array
(
[0] => stdClass Object
(
[day] => 1
[time] => 55
[name] => Running
[cycle] => 2
)
[1] => stdClass Object
(
[day] => 5
[time] => 15
[name] => Running
[cycle] => 2
)
)
[id] => 36848901
)
所需的结构是:
stdClass Object
(
[day] => 1
[name] => Running
[cycle] => Array
(
[0] => stdClass Object
(
[time] => 60
[cycle] => 1
[day] => 1
)
[1] => stdClass Object
(
[time] => 55
[cycle] => 2
[day] => 1
)
)
[id] => 36848901
)
stdClass Object
(
[day] => 5
[name] => Running
[cycle] => Array
(
[0] => stdClass Object
(
[time] => 30
[cycle] => 1
[day] => 5
)
[1] => stdClass Object
(
[time] => 15
[cycle] => 2
[day] => 5
)
)
[id] => 1237465
)
我需要程序然后使用foreach [day]然后在[cycle]循环遍历数组,以产生如下内容:
name day cycle 1 cycle 2 cycle ..
Running 1 60 55 ..
Running 5 30 15 ..
..
它只能逐行执行。我对此过程的这一部分没有太多控制。
我试图通过使用foreach循环和类似这样的数组命令来更改结构:
$newArray[] = array( "name" => $this->name, "day" => $this->day,
array("cycle" => $this->cycle, array("time" => $this->time, "cycle" =>
$this->cycle, "day" => $this->day)));
这给了我一种结构,几乎每个条目都正确,但不是全部都结合在一起。 为了结合它们,我尝试了array_merge_recursive()和各种变体,但是没有运气。
所以我认为我需要合并对象的数组,然后更改结构以将每个[时间]和[天]的值嵌套在[周期]内,以便我可以遍历它们。
最好的方法是什么?
它在PHP 7.2上运行。
更多我尝试的代码:
// get {data} part of JSON-encoded field for each mysql result
for ($x = 0; $x < $this->cycleCount; $x++) {
preg_match("/{.*}/",$this->tmpString[$x]['data'],$matches);
$this->data[$x] = json_decode($matches[0]);
foreach ($this->data[$x] as $day) {
$newArray[] = array( "name" => $day->name, "day" => $day->day,
array("cycle" => $day->cycle,
array("time" => $day->time,
"cycle" => $day->cycle,
"day" => $day->day)
)
);
}
答案 0 :(得分:0)
$data = array();
$object = json_decode($querObject,true);
foreach($object as $day => $info)
{
foreach($info['cycle'] as $cycleInfo)
{
$data[$info['$id']]['name'] = $cycleInfo['name'];
$data[$info['$id']]['day'] = $cycleInfo['day'];
$data[$info['$id']]['id'] = $cycleInfo['id'];
$data[$info['$id']]['cycle'][] =array('time'=>$cycleInfo['time'],'cycle'=>$cycleInfo['cycle'],'day'=>=>$cycleInfo['day']);
}
}