-2

Issue

New to PHP, trying to parse the values of an associative array that is in a list in PHP.

I come from a Pythonic background and am faced with refactoring a code I wrote in Python to a PHP CLI Script. Working Pythonic Script - https://replit.com/@Terry-BrooksJr/AccesingDataAPI?v=1 (Note: To see Output CSV must edit in workspace)

Sample Payload

https://pastebin.com/XF9vHeW2

Having Trouble with Accessing the Nested Values in an Assoc. Array. - Seeing Note 4. IN PHP attempt

Here is the Function in Question: Python

def processSessions():
... Stuff to Open CVS File Pointer/Context Manager ... 
        for session in sessions['data']:
            for scoring in session['responses']:
                row_data = session['session_id'],scoring['question_reference'],scoring['question_type'],scoring['score'],scoring['max_score']
                csv_writer.writerow(row_data)

PHP Attempt

function processSessions()
{

    $sessionDataCSV = 'SessionData'. date("Y-m-d") .'.csv';
    $sessions = downloadSessions();
    //NOTE - 1. Marshal/Serializes JSON Session Data to PHP Data Structure (associative array) Using json_decode() method
    $associoatedSessionDataArray = $sessions;

    //NOTE - 2. Opens File pointer to CSV Output
    $csv_output_file_pointer = fopen($sessionDataCSV, 'w');

    //NOTE - 3. Writes field names
    $fieldNames = array(
                        "ID",
                        "Reference",
                        "Type",
                        "Score",
                        "MaxScore"
                        );
    echo($associoatedSessionDataArray['data']);
    fputcsv($csv_output_file_pointer, $fieldNames);
    if (is_array($associoatedSessionDataArray) || is_object($associoatedSessionDataArray))
    {
     // NOTE - 4. Loop to Write Records
        foreach ($associoatedSessionDataArray as $session) {
            foreach ($associoatedSessionDataArray as $scoring) 
            fputcsv($csv_output_file_pointer, [$session['session_id'],$scoring['question_reference'],$session['question_type'],$session['score'],$session['max_score']]);

        }
    }
    // }
    else // If $myList was not an array, then this block is executed. 
    {
  echo "Unfortunately, an error occured.";
    }

    //NOTE - 5. Closes File pointer to CSV Output
    fclose($csv_output_file_pointer);
}

Unexpected Output

ID,Reference,Type,Score,MaxScore
a9c92dc1-725c-456a-acc9-cdd32fd9f81b,,,6,8
ecc0bdb2-2fc9-4489-b2d6-b818a8b0ebc0,,,16,19
ee5ed0c3-f590-40d0-8480-8037914738ba,,,1,2

My Ask

  • Explain Why the Script is NOT iterating thru the entire list of responses data['data']['responses'] (See Paste Bin link in #Sample Payload
  • Why the output csv is NULL for the Reference,Type fields but parses and extracts the score and max_score when they are on the same level in terms of nesting.
8
  • It's not clear what the problem is. A PHP associative array is analogous to a Python dictionary. The nested loops should be similar. Commented Jun 15, 2023 at 16:14
  • What do you get in your CSV file? Commented Jun 15, 2023 at 16:15
  • But your PHP code seems to be processing ordinary lists, not dictionaries. How are you getting associative arrays instead of indexed arrays in PHP? Commented Jun 15, 2023 at 16:15
  • Maybe if you showed us an example of the data in $sessions and then an example of the output you want, the middle bit (FLOC) would be easier for us to help you with Commented Jun 15, 2023 at 16:17
  • 1
    foreach ($associoatedSessionDataArray['data'] as $session) { foreach ($session['responses'] as $scoring) { ... } } Commented Jun 15, 2023 at 16:58

1 Answer 1

1

I suggest you replace this part:

foreach ($associoatedSessionDataArray as $session) {
    foreach ($associoatedSessionDataArray as $scoring) 
    fputcsv($csv_output_file_pointer, [$session['session_id'],$scoring['question_reference'],$session['question_type'],$session['score'],$session['max_score']]);
}

with:

foreach ($associoatedSessionDataArray as $session) {
    foreach ($session['responses'] as $scoring) {
        fputcsv($csv_output_file_pointer, [
           $session['session_id'],
           $scoring['question_reference'],
           $scoring['question_type'],
           $scoring['score'],
           $scoring['max_score'],
        ]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, just seen your question has been updated. I think you're missing some data because you're using $session where you should have $scoring in some of the CSV output values. You also have an error in the definitions of what you are looping over - see my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.