解析嵌套的关联数组列表的值 PHP

huangapple go评论96阅读模式
英文:

Parsing nested Values of AC list of Associative Arrays PHP

问题

问题

我刚开始学习PHP,尝试解析PHP中列表中的关联数组的值。

我来自Python的背景,现在面临着将我在Python中编写的代码重构成PHP CLI脚本的任务。
工作中的Python脚本 - https://replit.com/@Terry-BrooksJr/AccesingDataAPI?v=1(注意:要查看输出的CSV,必须在工作空间中进行编辑)

示例负载

https://pastebin.com/XF9vHeW2

在访问嵌套的关联数组值方面遇到了问题。- 请参阅Note 4. PHP尝试

以下是问题所在的函数:
Python

  1. def processSessions():
  2. ... 打开CSV文件指针/上下文管理器的操作 ...
  3. for session in sessions['data']:
  4. for scoring in session['responses']:
  5. row_data = session['session_id'], scoring['question_reference'], scoring['question_type'], scoring['score'], scoring['max_score']
  6. csv_writer.writerow(row_data)

PHP尝试

  1. function processSessions()
  2. {
  3. $sessionDataCSV = 'SessionData'. date("Y-m-d") .'.csv';
  4. $sessions = downloadSessions();
  5. //注意 - 1. 使用json_decode()方法将JSON会话数据编组/序列化为PHP数据结构(关联数组)
  6. $associoatedSessionDataArray = $sessions;
  7. //注意 - 2. 打开CSV输出的文件指针
  8. $csv_output_file_pointer = fopen($sessionDataCSV, 'w');
  9. //注意 - 3. 写入字段名称
  10. $fieldNames = array(
  11. "ID",
  12. "Reference",
  13. "Type",
  14. "Score",
  15. "MaxScore"
  16. );
  17. echo($associoatedSessionDataArray['data']);
  18. fputcsv($csv_output_file_pointer, $fieldNames);
  19. if (is_array($associoatedSessionDataArray) || is_object($associoatedSessionDataArray))
  20. {
  21. // 注意 - 4. 循环写入记录
  22. foreach ($associoatedSessionDataArray as $session) {
  23. foreach ($associoatedSessionDataArray as $scoring)
  24. fputcsv($csv_output_file_pointer, [$session['session_id'],$scoring['question_reference'],$session['question_type'],$session['score'],$session['max_score']]);
  25. }
  26. }
  27. // }
  28. else // 如果$myList不是数组,则执行此块。
  29. {
  30. echo "Unfortunately, an error occured.";
  31. }
  32. //注意 - 5. 关闭CSV输出文件的文件指针
  33. fclose($csv_output_file_pointer);
  34. }

预期之外的输出

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

我的问题

  • 解释为什么脚本没有遍历整个响应列表data['data']['responses'](请参阅#示例负载中的Paste Bin链接)
  • 为什么输出的CSV对于“Reference”、“Type”字段为NULL,但在嵌套层次相同的情况下解析和提取了“score”和“max_score”。
英文:

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

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

PHP Attempt

  1. function processSessions()
  2. {
  3. $sessionDataCSV = 'SessionData'. date("Y-m-d") .'.csv';
  4. $sessions = downloadSessions();
  5. //NOTE - 1. Marshal/Serializes JSON Session Data to PHP Data Structure (associative array) Using json_decode() method
  6. $associoatedSessionDataArray = $sessions;
  7. //NOTE - 2. Opens File pointer to CSV Output
  8. $csv_output_file_pointer = fopen($sessionDataCSV, 'w');
  9. //NOTE - 3. Writes field names
  10. $fieldNames = array(
  11. "ID",
  12. "Reference",
  13. "Type",
  14. "Score",
  15. "MaxScore"
  16. );
  17. echo($associoatedSessionDataArray['data']);
  18. fputcsv($csv_output_file_pointer, $fieldNames);
  19. if (is_array($associoatedSessionDataArray) || is_object($associoatedSessionDataArray))
  20. {
  21. // NOTE - 4. Loop to Write Records
  22. foreach ($associoatedSessionDataArray as $session) {
  23. foreach ($associoatedSessionDataArray as $scoring)
  24. fputcsv($csv_output_file_pointer, [$session['session_id'],$scoring['question_reference'],$session['question_type'],$session['score'],$session['max_score']]);
  25. }
  26. }
  27. // }
  28. else // If $myList was not an array, then this block is executed.
  29. {
  30. echo "Unfortunately, an error occured.";
  31. }
  32. //NOTE - 5. Closes File pointer to CSV Output
  33. fclose($csv_output_file_pointer);
  34. }

Unexpected Output

  1. ID,Reference,Type,Score,MaxScore
  2. a9c92dc1-725c-456a-acc9-cdd32fd9f81b,,,6,8
  3. ecc0bdb2-2fc9-4489-b2d6-b818a8b0ebc0,,,16,19
  4. 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.

答案1

得分: 1

建议您将此部分替换为:

英文:

I suggest you replace this part:

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

with:

  1. foreach ($associoatedSessionDataArray as $session) {
  2. foreach ($session['responses'] as $scoring) {
  3. fputcsv($csv_output_file_pointer, [
  4. $session['session_id'],
  5. $scoring['question_reference'],
  6. $scoring['question_type'],
  7. $scoring['score'],
  8. $scoring['max_score'],
  9. ]);
  10. }
  11. }

huangapple
  • 本文由 发表于 2023年6月16日 00:12:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定