PHP改变数组结构和设置状态

时间:2014-11-20 06:16:01

标签: php arrays multidimensional-array

PHP代码:

foreach ($fetch_res as $res){

        echo '<pre>';print_r($res);
}

生成数组:

Array
(
    [USERID] => 13663
    [PROJID] => 999
    [ENTRYDATE] => 13-NOV-14
    [STARTDATE] => 01-NOV-14
    [ENDDATE] => 20-NOV-14
    [ACTIVE] => 123
    [ALLOCATION] => 456
)

Array
(
    [USERID] => 13664
    [PROJID] => 999
    [ENTRYDATE] => 13-NOV-14
    [STARTDATE] => 01-NOV-14
    [ENDDATE] => 20-NOV-14
    [ACTIVE] => 124
    [ALLOCATION] => 457
)

而以下字段具有各自的ID和基于ID

的状态

ALLOCATION - 456(Y) / DEALLOCAION - 457(N) 
ACTIVE - 123(Y) / INACTIVE - 124(N)

使用以上信息,我如何生成以下所需的数组格式

array("ProjId"=>999,
      "RS"=>array( //ALLOCATION ACTIVE
         0=>array("13663","N","Y")
         1=>array("13664","N","Y")
     )
);

RS是资源ID,其中NY表示状态。

感谢。

2 个答案:

答案 0 :(得分:1)

粗略编码。你可以用自己的风格进行改进。

  foreach ($fetch_res as $res){
    if($res["ALLOCATION"] == "456")$allocation = "Y";
    else $allocation = "N";
    if($res["ACTIVE"] == "123")$active = "Y";
    else $active = "N";

    $result[$res["PROJID"]][] = array($res["USERID"],$allocation,$active));
  }

答案 1 :(得分:0)

$data = array();
foreach ($fetch_res as $res){
    $data['ProjId'] = $res['PROJID'];
    $data['RS'][] = array($res['USERID'], ($res['ALLOCATION'] == 456) ? "Y" : "N", ($res['ALLOCATION'] == 123) ? "Y" : "N");
}

如果你需要它作为字符串然后 -

$data['RS'][] = '"'.$res['USERID'].','. ($res['ALLOCATION'] == 456) ? "Y" : "N".','. ($res['ALLOCATION'] == 123) ? "Y" : "N".'"';