将键值对添加到多维数组

我有一个二维数组,我试图在外部数组上循环,$jsonarray并'color'根据开关的输出向内部数组添加一个键值对。当我以 JSON 格式显示输出时,'color'字段全部设置为 null。其$jsonarray结构如下:


$jsonarray= [

    0=> [

        'deadline'     => 'deadline',

        'duedate'  => 'duedate',],

    1=> [

        'deadline'     => 'deadline',

        'duedate'  => 'duedate',],


我的代码如下所示:


    $i = 0;

    $keys = array_keys($jsonarray);

    for ($k = 0; $k < count($jsonarray); $k++){

   foreach ($jsonarray[$keys[$k]] as $key => $value) {

     $color = 0;

     switch ($i) {

       case 0:

         $color = '#AED5F1';

         break;

       case 1:

         $color = '#F7D590';

         break;

       case 2:

         $color = '#EE8970';

         break;

     }

    array_push($jsonarray[$k]['color'], $color);

     $i++;

      }

    }

我怎样才能解决这个问题?


沧海一幻觉
浏览 71回答 1
1回答

PIPIONE

尝试这个:foreach ($jsonarray as $i => &$value) {&nbsp; &nbsp; switch ($i) {&nbsp; &nbsp; &nbsp; &nbsp; case 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $value['color'] = '#AED5F1';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $value['color'] = '#F7D590';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case 2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $value['color'] = '#EE8970';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP