2014-07-23 60 views
0

我有一個從php查詢返回的數組。結果就是這樣。關聯數組中新增元素的重命名鍵

好,這裏是對發送之前循環剛過選擇做

$row = $stmt->fetchAll(); 
    $arraySize = sizeof($row); 

    for($x = 0; $x < $arraySize;$x++) 
    { 

     // Gets rid of all the numeric KEY values 
     $max = sizeof($row[$x])/2; 
     for($i = 0; $i < $max;$i++) 
     { 
      unset($row[$x][$i]); 
     } 

     $row[$x][] = false; // appends a boolean value for the tick box in datatables 
     $row['select'] = $row['9']; 
     unset($row['9']); 

     $json[] = $row[$x]; 
    } 
echo json_encode($json); 
Array 
    (
     [0] => Array 
      (
       [uuid] => 365 
       [name] => August_Kidsmeals.mp4 
       [title] => 
       [path] => file://C:/wamp/www/chopperv2/video/library/ 
       [duration] => 00:30:00 
       [uploaded_date] => 2014-07-22 
       [uploaded_by] => admin 
       [keyword] => 
       [comment] => 
      ) 

     [1] => Array 
      (
       [uuid] => 368 
       [name] => August_breakfast.mp4 
       [title] => 
       [path] => file://C:/wamp/www/chopperv2/video/library/ 
       [duration] => 00:30:00 
       [uploaded_date] => 2014-07-22 
       [uploaded_by] => admin 
       [keyword] => 
       [comment] => 
      ) 
    ) 

現在我要推一個額外的元素添加到陣列(「選擇」)通過AJAX轉換爲數據表。

我想自定義推送元素的KEY,但林有這種困難。

我試過這個。哪些工作,但它的數字。

$ row [$ x] [] = true;

它的一部分For loop。這導致的[9] => 1

'appendation' 我試圖[9]的東西重命名這樣

$row['select'] = $row['9']; 
unset($row['9']); 

,但無濟於事。請有人給我正確的方向。

這應該是結果

[0] => Array 
     (
      [uuid] => 365 
      [name] => August_Kidsmeals.mp4 
      [title] => 
      [path] => file://C:/wamp/www/chopperv2/video/library/ 
      [duration] => 00:30:00 
      [uploaded_date] => 2014-07-22 
      [uploaded_by] => admin 
      [keyword] => 
      [comment] => 
      [select] => 1  // <<------ I WANT THIS 
     ) 
+0

顯示期望的結果陣列 – hindmost

+0

我認爲你必須提供更多的代碼,很難從這裏想你是怎麼做的 – Ghost

+0

什麼是'$ x'?你從哪裏得到這個'selected'?你需要更多地縮小你的問題。 – Darren

回答

1

一個簡單的foreach應該就足夠了,並且在每個副本上使用&引用:

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // no need to unsetting numeric indexed values, all are in associative now 
foreach($rows as &$row) { 
    $row['selected'] = true; 
} 
+0

好吧,謝謝,但那不是重點。是的是'PDO :: FETCH_ASSOC',但我想在每個數組的末尾附加一個自定義的'KEY => VALUE'。 我想追加的'SELECT''鍵不會返回查詢 – morne

+0

@mornenel等待你甚至嘗試過嗎?這附加在每個陣列的末尾 – Ghost

+0

好東西的人,謝謝 – morne

0

只需元素添加到所需的行中的循環: (也許,如果你olny希望所選行的整個結果)

if(9 == $x) { 
$row[$x]['select'] = 1; 
$result = $row[$x]; 
break; 
}