从数组转换数组时遇到问题

时间:2021-06-07 19:03:30

标签: php arrays multidimensional-array

我有这样的数组

Array
(
    [ID] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )

    [Ticket_ID] => Array
        (
            [0] => e
            [1] => f
            [2] => g
            [3] => h
        )

    [Status] => Array
        (
            [0] => i
            [1] => j
            [2] => k
            [3] => l
        )
)

我想要这样

Array
(
    [0] => Array
        (
            [ID] => a
            [Ticket_ID] => e
            [Status] => i
        )

    [1] => Array
        (
            [ID] => b
            [Ticket_ID] => f
            [Status] => j
        )

    [2] => Array
        (
            [ID] => c
            [Ticket_ID] => g
            [Status] => k
        )
    [3] => Array
        (
            [ID] => d
            [Ticket_ID] => h
            [Status] => l
        )
)

这是我目前的代码:

foreach($array as $k => $v) { 
  if($k = 'ns0:Request_ID') { 
      foreach($v as $kk => $vv) { 
          array_push($sd ,$vv); 
      } 
  } 
  break; 
 }

1 个答案:

答案 0 :(得分:1)

//assuming initial data is in variable $data
$finalArray = [];

//assume that each "record" has an "ID" and as such the number of "ID" items
//will determine the number of records
if(isset($data['ID']) && is_array($data['ID'])){
    //determine number of records/items based on number of id elements
    $noOfItems = count($data['ID']);

    //foreach item check if an element exists in the respective
    //"Ticket_ID" and "Status" arrays based on the current index "$i"
    //Checks were included to ensure values were arrays and indexes were
    //present before use usinf `isset` and `is_array`. 
    // if a value did not exist for this index `null` was assigned.

    for($i=0;$i<$noOfItems;$i++){
         array_push($finalArray,[
             'ID'=>$data['ID'][$i],
             'Ticket_ID'=> ( 
                              isset($data['Ticket_ID']) &&  
                              is_array($data['Ticket_ID']) &&
                              isset($data['Ticket_ID'][$i])
                           ) ? $data['Ticket_ID'][$i] : null,
             'Status'=> ( 
                              isset($data['Status']) &&  
                              is_array($data['Status']) &&
                              isset($data['Status'][$i])
                           ) ? $data['Status'][$i] : null
         ]);
    }
}
//final results are in $finalArray