簡體   English   中英

使用foreach創建多維StdClass對象數組

[英]Create multi-dimensional StdClass Object array with foreach

我試圖創建一個多維的StdClass對象,但是輸出始終來自第一個和第二個foreach循環的最后一個循環,而不是所有循環的集合。

每一天應該有3個$ exercises。 有5天,但只有1天有1次鍛煉。

功能和當前輸出: http : //paste.laravel.com/WIU

似乎正在發生的事情是您每次循環都覆蓋data對象的days屬性。 而不是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.

每天添加多個練習也可以使用相同的方法。

簡單對象將投放時,對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"}]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM