Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mbadamchi@gmail.com's avatar

Loop inside JSON Array

I try to loop through json data like this:

[
    {
        id: 15215,
        cv: {
            cv_id: 15709,
            
            skills: [
                {
                skill_id: 117498
                }
            ],
            education: [
                {
                edu_id: 24835
                }
            ],
            city: {
                id: 176
            }
        }
    }
]

with these codes:

public function cvSearch(Request $request){ 
    $jobTitle = $request->input('jobTitle');
    $cityId = $request->input('cityId');
    $cvs = Cv_srch::with(
            array(
                'Cv.skills'=>function ($query)
                { $query->orderBy('skill_id', 'desc'); },
                'Cv.education'=>function ($query)
                { $query->orderBy('education_id', 'desc'); },
                'Cv.city'
            )
        )
        ->where('prsn_city', $cityId)
        ->where('prsn_srch', 'like', '%'.$jobTitle.'%')
        ->get();

    foreach($cvs as $k=>$cv) {
        $workTitle = $cv['cv']->cv_worktype;
    }
    return $cvs;
}

but, after $workTitle all other nested array will be omitted in the loop result! i.e. the result will remove skills and education!!!! What is the problem? and how can i Solve it?

0 likes
6 replies
tomopongrac's avatar

Why don't you decode json with json_decode() and then loop like regular loop with foreach

EmilMoe's avatar
$array = json_decode('[
    {
        id: 15215,
        cv: {
            cv_id: 15709,
            
            skills: [
                {
                skill_id: 117498
                }
            ],
            education: [
                {
                edu_id: 24835
                }
            ],
            city: {
                id: 176
            }
        }
    }
]');
tomopongrac's avatar
Level 51

Like this

$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');

foreach($arr as $item) { //foreach element in $arr
    $uses = $item['var1']; //etc
}

Please or to participate in this conversation.