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
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
NULLfor theReference,Typefields but parses and extracts thescoreandmax_scorewhen they are on the same level in terms of nesting.
$sessionsand then an example of the output you want, the middle bit (FLOC) would be easier for us to help you withforeach ($associoatedSessionDataArray['data'] as $session) { foreach ($session['responses'] as $scoring) { ... } }