Skip to content
Advertisement

PHP ForEach Array – display variables

I have a Curl query which outputs JSON as $response

$response = curl_exec($curl);
$response = json_decode($response, true);

I have turned this into the below Array:

Array
(
    [results] => Array
        (
            [0] => Array
                (
                    [jobId] => 41682277
                    [employerId] => 630007
                    [employerName] => ABC
                    [employerProfileId] => 
                    [employerProfileName] => 
                    [jobTitle] => Internal Sales Negotiator/Sales Executive

How can I loop through this array, to show each job on a website. I need to turn some of the fields into variables, for example, jobTitle

I have tried the below but nothing is output back;

foreach ($response as $job) {
    foreach ($job->results as $record) {
        $ID = $record->jobId;
        echo"JobID= $ID<br>";
        
    }
}

Advertisement

Answer

According to your array structure, the following code snippet should do the trick. You decode your JSON payload as an associative array by adding the second argument of true to the json_decode function, so it shouldn’t being accessed as an object.

<?php

$response = [
    'results' => [
        [
            'jobId'               => 41682277,
            'employerId'          => 630007,
            'employerName'        => 'employerName',
            'employerProfileId'   => '',
            'employerProfileName' => 'employerProfileName',
            'jobTitle'            => 'Internal Sales Negotiator/Sales Executive',
        ],
    ],
];

foreach ($response['results'] as $record) {
    $id = $record['jobId'];
    echo "JobID = $id<br>";
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement