2015-09-29 28 views
-1

這是我的PHP函數PHP數組想擁有價值

public function pointComplete() { 

     $inputs = Input::all(); 

     print_r("<pre>"); 
     print_r($inputs); 
     print_r("</pre>"); 
} 

輸出如下:

Array 
(
    [_token] => 2lIrWksIlJHjHASKAS0UDDSYLtcYwsDYCuxhjQ32 
    [complete] => Complete 
    [post_id_9] => 1 
    [post_id_10] => 
    [post_id_12] => 2 
    [post_id_13] => 
    [post_id_14] => 
) 

我想這個PHP數組:

array (
    "post1" => array(
     "id" => "9", 
     "point" => "1" 
    ), 
    "post2" => array(
     "id" => "12", 
     "point" => "1" 
    ) 
); 
+1

那已經在數組 –

+0

但我只想輸入post_id = 9,value = 1和post_id = 12,value = 2 –

+3

抱歉,現在有人真的知道你在問什麼 –

回答

1

一你可以這樣做的方式是循環輸入,並解析密鑰。然後把你解析的結果放入另一個數組中。

$post_id = 1; 
$posts = array(); 

foreach ($inputs as $key => $value) { 
    $explode = explode('post_id_', $key); 
    if (count($explode) == 2 && $value !== null) { 
     $id = $explode[1]; 
     $posts['post'.$post_id] = array('id' => $id, 'value' => $value); 
     $post_id++; 
    } 
} 

print_r($posts) will yield:

Array 
(
    [post1] => Array 
     (
      [id] => 9 
      [value] => 1 
     ) 

    [post2] => Array 
     (
      [id] => 12 
      [value] => 2 
     ) 

) 

雖然我真的只是採取在面值這裏這個問題。實現你想要做的事情可能有一個更簡單的方法。

+0

你可以爆炸'post_id_'可能是一個小清潔 –

+0

@Dagon好主意。感謝您的建議。 – Zsw

+0

謝謝@Zsw我想要那樣。 –