我正在尝试创建一个多维StdClass对象,但输出始终来自第一个和第二个foreach循环的最后一个循环,而不是所有循环的集合。
每天应该有3美元的练习。并且有5天,但只有1天进行1次锻炼。
功能&电流输出: http://paste.laravel.com/WIU
答案 0 :(得分:5)
看起来发生的事情是,每次循环时,您都会覆盖days
对象的data
属性。而不是stdClass
,$data->days
应该是一个数组,然后你应该将描述每一天的stdClass
个对象添加到该数组......就像这样(使用部分代码来自周围)第14行:
$data->days = array(); //create the array
foreach ($jsonDays as $day)
{
$newDay = new stdClass(); //create a day object
$newDay = $day->day; //add things to the day object
...
$data->days[] = $newDay; //push the day object onto your day array.
同样的方法也适用于每天添加多个练习。
答案 1 :(得分:0)
当简单对象服务时,没有特别需要stdObjects。这是一个用于存储数据数组的简单多维对象结构。
<?php
//create exercise array: 3 exercise rows x 5 day columns
$ex[0] = ["aa", "ab", "ac", "ad", "ae"];
$ex[1] = ["ba", "bb", "bc", "bd", "be"];
$ex[2] = ["ca", "cb", "cc", "cd", "ce"];
//create your day class for the 3 exercises
class day{
public $ex0;
public $ex1;
public $ex2;
}
//create your period (days) class for all the days
class days{
public $days;
}
//create objects for each day of exercises and store the exercises
for($i=0;$i<count($ex[0]);$i++){ //for each of 5 days
$day[$i] = new day();
$day[$i]->ex0 = $ex[0][$i];//1st exercise of the i_th day
$day[$i]->ex1 = $ex[1][$i];//2nd exercise of the i_th day
$day[$i]->ex2 = $ex[2][$i];//3rd exercise of the i_th day
}
//create an object for all the data
$days = new days;
//store the array of day objects with their data in the days object
$days->days = $day;
//confirm object creation and structure
print_r($days);
//check the json_encode result
echo "<br><br>" . (json_encode($days)) . "<br>";
?>
结果:
days Object ( [days] => Array (
[0] => day Object ( [ex0] => aa [ex1] => ba [ex2] => ca )
[1] => day Object ( [ex0] => ab [ex1] => bb [ex2] => cb )
[2] => day Object ( [ex0] => ac [ex1] => bc [ex2] => cc )
[3] => day Object ( [ex0] => ad [ex1] => bd [ex2] => cd )
[4] => day Object ( [ex0] => ae [ex1] => be [ex2] => ce ) ) )
{"days":[{"ex0":"aa","ex1":"ba","ex2":"ca"},
{"ex0":"ab","ex1":"bb","ex2":"cb"},{"ex0":"ac","ex1":"bc","ex2":"cc"},
{"ex0":"ad","ex1":"bd","ex2":"cd"},{"ex0":"ae","ex1":"be","ex2":"ce"}]}