0

我有關聯數組稱爲$data如下:操縱

foreach ($data['pt_doc_title'] as $key => $title) { 

     $id = isset($data['pt_doc_id'][$key-1])   ? $data['pt_doc_id'][$key-1]   : null; 
     $data['pt_documents_data'][] = array(
     'pt_doc_title'  => $title, 
     'pt_doc_id'   => $id 
    );   
    } 
unset($data['pt_doc_title'], $data['pt_doc_id']); 

後:

Array 
(
    [op] => edit 
    [pt_id] => 4 
    [form_submitted] => yes 
    [pt_doc_title] => Array 
     (
      [1] => Test Document 
      [2] => New Joining 
      [3] => Hallo Jolly 
     ) 

    [pt_doc_id] => Array 
     (
      [0] => 6 
      [1] => 7 
     ) 



    [submit] => Update 
) 

爲了保持所有的包裝類型的文檔數據一起我如下操作上述陣列我得到以下數組$data如下:

Array 
    (
     [op] => edit 
     [pt_id] => 4 
     [form_submitted] => yes 

     [submit] => Update 
     [pt_documents_data] => Array 
      (
       [0] => Array 
        (
         [pt_doc_title] => Test Document 
         [pt_doc_id] => 6 
        ) 

        [1] => Array 
         (
          [pt_doc_title] => New Joining 
          [pt_doc_id] => 7 
         ) 

        [2] => Array 
         (
          [pt_doc_title] => Hallo Jolly 
          [pt_doc_id] => 
         ) 

       ) 

     ) 

我的問題是我h創建另一個名爲$_FILES的數組,如下所示,我想以相同的方式將其中一個鍵(名稱)合併到上面的數組中。

Array 
(
    [document_file_name_1] => Array 
     (
      [name] => 
      [type] => 
      [tmp_name] => 
      [error] => 4 
      [size] => 0 
     ) 

    [document_file_name_2] => Array 
     (
      [name] => 
      [type] => 
      [tmp_name] => 
      [error] => 4 
      [size] => 0 
     ) 

    [document_file_name_3] => Array 
     (
      [name] => FAQ.doc 
      [type] => application/msword 
      [tmp_name] => /tmp/phpFiBYKB 
      [error] => 0 
      [size] => 35840 
     ) 

) 

這就是說,如果在[name]下面存在一個值,那麼最終的數組應該如下。因爲有一個值目前僅在數組的最後一個數組元素$_FILES

Array 
    (
     [op] => edit 
     [pt_id] => 4 
     [form_submitted] => yes 
     [submit] => Update 
     [pt_documents_data] => Array 
      (
       [0] => Array 
        (
         [pt_doc_title] => Test Document 
         [pt_doc_id] => 6 
         [pt_doc_file_iname] => 
        ) 

      [1] => Array 
       (
        [pt_doc_title] => New Joining 
        [pt_doc_id] => 7 
        [pt_doc_file_iname] => 
       ) 

      [2] => Array 
       (
        [pt_doc_title] => Hallo Jolly 
        [pt_doc_id] => 
        [pt_doc_file_iname] => FAQ.doc 
       ) 

     ) 

) 

任何人都可以請幫我在創造這樣的最終陣列的?

回答

1

最簡單的方法是步行$_FILES數組,然後從字段名的最後一段提取id ...然後使用-1作爲將文件添加到結果數組的基礎。

像這樣的東西應該讓你有(未經測試):

foreach($_FILES as $k => $file){ 
    $index_to_update = trim(substr($k, strrpos($k, "_")+1))-1; 
    $res["pt_document_data"][$index_to_update]["pt_doc_file_iname"] = isset($file["name"])?$file["name"]:""; 
} 

這是假設$水庫是作爲pt_document_data元素的父元素的數組。

相關問題