/    Sign up×
Community /Pin to ProfileBookmark

Nested Arrays based on SQL results

I’m doing a query on my database, returning all records. I’m doing a calculation to get the decade it was set for.

Each record has a year, 2021 for example. So I’m doing this

[code]
floor(`courseYear`/10)*10 desc
[/code]

That works.

I’ve also got levels 1, 2 and 3.

What I’m trying to do is. Have an array for each decade, and an array inside that array for each level. This nested array will have all the courses inside it.

My aim is to loop through each decade. Then loop through each level and print the courses.

My SQL is ordered by decade and level type.

here’s my code, which is failing. I’m lost and looking for help. I’m not even sure if this is the best approch

[code]
$decade = 0;
$decadeRow = array();

if ($numRows > 0){
while($row = $result->fetch_assoc()){

if ($decade != $row[‘decade’]){

if ($decade > 0){
$decadeRow[] = array(‘Decade’ => $decade, ‘Beginner’=> $beg, ‘Intermediate’ => $inter, ‘Advanced’ => $advd);
}
// Decade is new or different from previous. Create new arrays
$beg= array();
$inter= array();
$advd= array();
}

$course= array(intval($row[‘courseId’]), $row[‘courseName’], intval($row[‘YearRun’]));

if ($row[‘courseType’] == 0){
$beg[] = $course;
} elseif ($row[‘courseType’] == 1){
$inter[] = $course;
} else {
$advd[] = $course;
}


}


}

return json_encode($decadeRow);
[/code]

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMay 16.2021 — Might be easier to answer if we could see what a result row from the query consists of (or several rows if we need to see how they get allocated to the final result), and an example of what you want as the final result -- either the array structure or the JSON structure.
Copy linkTweet thisAlerts:
@kiwisauthorMay 16.2021 — @NogDog#1631656

Yeah sure,

Here's a sample

courseId | courseName | courseYear | courseLevel

1, 'Testing Topic', 2021, 0

2 'Another Topic' 2021 1

3 'Rowing', 2018, 3
Copy linkTweet thisAlerts:
@NogDogMay 16.2021 — Is this close to what you need?
[code=php]
$data = array();
while ($row = $result->fetch_assoc()) {
$data[$row['courseYear']]['level'][$row['courseLevel']][$row['courseId']] = $row['courseName'];
}
[/code]

Using your sample data and processing it as an array, I get:
[code=php]
$result = [
[
'courseId' => 1,
'courseName' => 'Testing Topic',
'courseYear' => 2021,
'courseLevel' => 0
],
[
'courseId' => 2,
'courseName' => 'Another Topic',
'courseYear' => 2021,
'courseLevel' => 1
],
[
'courseId' => 3,
'courseName' => 'Rowing',
'courseYear' => 2018,
'courseLevel' => 3
],
];
$data = array();
foreach($result as $row) {
$data[$row['courseYear']]['level'][$row['courseLevel']][$row['courseId']] = $row['courseName'];
}
echo json_encode($data, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
[/code]

Output:
[code=json]
{
"2021": {
"level": {
"0": {
"1": "Testing Topic"
},
"1": {
"2": "Another Topic"
}
}
},
"2018": {
"level": {
"3": {
"3": "Rowing"
}
}
}
}
[/code]
Copy linkTweet thisAlerts:
@kiwisauthorMay 16.2021 — @NogDog#1631674

I didn't realize this simple approach could work. I always over complicate array's

<i>
</i>$data = array();
while ($row = $result-&gt;fetch_assoc()) {
$data[$row['courseYear']]['level'][$row['courseLevel']][$row['courseId']] = $row['courseName'];
}


As it's being done inside an OOP function, I'm returning is like this

<i>
</i>return json_encode($data);


On my public page I'm doing this

<i>
</i>$courseArray= json_decode($CourseList-&gt;getAllCoursesByDecade());
var_dump($courseArray);
foreach($courseArrayas $Decade){
echo $Decade;

<i> </i> }
<i> </i>

But I get this error


Fatal error

: Uncaught Error: Object of class stdClass could not be converted to string in /home2/user/public_html/mydomain.com/courses.php:38 Stack trace: #0 {main} thrown in

/home2/user/public_html/mydomain.com/courses.php

on line

38
Copy linkTweet thisAlerts:
@NogDogMay 16.2021 — Try adding a true second parameter to the json_decode() call, which will make all parts of the result arrays (instead of converting JSON objects to PHP objects).
[code=php]
$courseArray= json_decode($CourseList->getAllCoursesByDecade(), true);
[/code]
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.8,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...