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

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

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

def processSessions():
... 打开CSV文件指针/上下文管理器的操作 ... 
        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尝试

function processSessions()
{

    $sessionDataCSV = 'SessionData'. date("Y-m-d") .'.csv';
    $sessions = downloadSessions();
    //注意 - 1. 使用json_decode()方法将JSON会话数据编组/序列化为PHP数据结构(关联数组)
    $associoatedSessionDataArray = $sessions;

    //注意 - 2. 打开CSV输出的文件指针
    $csv_output_file_pointer = fopen($sessionDataCSV, 'w');

    //注意 - 3. 写入字段名称
    $fieldNames = array(
                        "ID",
                        "Reference",
                        "Type",
                        "Score",
                        "MaxScore"
                        );
    echo($associoatedSessionDataArray['data']);
    fputcsv($csv_output_file_pointer, $fieldNames);
    if (is_array($associoatedSessionDataArray) || is_object($associoatedSessionDataArray))
    {
     // 注意 - 4. 循环写入记录
        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 // 如果$myList不是数组,则执行此块。
    {
  echo "Unfortunately, an error occured.";
    }

    //注意 - 5. 关闭CSV输出文件的文件指针
    fclose($csv_output_file_pointer);
}

预期之外的输出

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

我的问题

  • 解释为什么脚本没有遍历整个响应列表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

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.

答案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'],
        ]);
    }
}

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:

确定