Adding an item to an associative array

后端 未结 5 1379
太阳男子
太阳男子 2020-12-12 20:02
//go through each question
foreach($file_data as $value) {
   //separate the string by pipes and place in variables
   list($category, $question) = explode(\'|\', $v         


        
相关标签:
5条回答
  • 2020-12-12 20:32

    I know this is an old question but you can use:

    array_push($data, array($category => $question));
    

    This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:

    array_push($data,$question);
    
    0 讨论(0)
  • 2020-12-12 20:33

    You can simply do this

    $data += array($category => $question);
    

    If your're running on php 5.4+

    $data += [$category => $question];
    
    0 讨论(0)
  • 2020-12-12 20:35

    I think you want $data[$category] = $question;

    Or in case you want an array that maps categories to array of questions:

    $data = array();
    foreach($file_data as $value) {
        list($category, $question) = explode('|', $value, 2);
    
        if(!isset($data[$category])) {
            $data[$category] = array();
        }
        $data[$category][] = $question;
    }
    print_r($data);
    
    0 讨论(0)
  • 2020-12-12 20:43

    For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this

     $data[$category]["test"] = $question
    

    you can then call it (to test out the result by:

    echo $data[$category]["test"];
    

    which should print $question

    0 讨论(0)
  • 2020-12-12 20:49

    before for loop :

    $data = array();
    

    then in your loop:

    $data[] = array($catagory => $question);
    
    0 讨论(0)
提交回复
热议问题