2015-12-02 54 views
1

如何解決此問題?堆棧中的方法將數組轉換爲數組

我預計結果爲1,點擊後按鈕詳細 請幫助我..

<?php 
    $_SESSION['array1'] = array("zero","one","two"); 
    print_r($_SESSION['array1']); 
?> 
<form action="" method="post"> 
<input type="hidden" value="<?php print_r($_SESSION['array1']); ?>" name="detailCart"> 
<input type="submit" value="Detail" name="detail" class="detail"> 
</form> 

<?php 

    if (isset($_POST['detail'])) { 
     session_start(); 
     print_r($_POST['detailCart']); 
     echo "<br>"; 
     print_r($_POST['detailCart'][1]); 
     // should result is one 
    } 
?> 
+0

你需要數組轉換爲變量?你嘗試了什麼? –

回答

1

您存儲陣列中SESSION第一件事,這樣你就可以在得到會話數據任何地方表單和其他表單不需要將該數據提交給外部。

與會話獲取數據

<?php 

    if (isset($_POST['detail'])) { 
     echo $_SESSION['array1'][0]; 
     echo $_SESSION['array1'][1]; 
     echo $_SESSION['array1'][2]; 
    } 
?> 

而不會話獲取數據

<?php 
    $_SESSION['array1'] = array("zero","one","two"); 
    print_r($_SESSION['array1']); 
?> 
<form action="" method="post"> 
<input type="hidden" value="<?php echo implode(',',$_SESSION['array1']); ?>" name="detailCart"> 
<input type="submit" value="Detail" name="detail" class="detail"> 
</form> 

<?php 

    if (isset($_POST['detail'])) { 
     session_start(); 
     echo $_POST['detailCart']; //string 
     $array = explode(",",$_POST['detailCart']); 
     echo '<br/>'; 
     echo $array[0];  
     echo '<br/>'; 
     echo $array[1]; 
     echo '<br/>'; 
     echo $array[2]; 

    } 
?> 

O/P

zero,one,two 
zero 
one 
two 

另一種方式

<?php 
     $_SESSION['array1'] = array("zero","one","two"); 
     print_r($_SESSION['array1']); 
    ?> 
    <form action="" method="post"> 

    <input type="hidden" value="<?php echo $_SESSION['array1'][0] ?>" name="detailCart[0]"> 

    <input type="hidden" value="<?php echo $_SESSION['array1'][1] ?>" name="detailCart[1]"> 

    <input type="hidden" value="<?php echo $_SESSION['array1'][2] ?>" name="detailCart[2]"> 
    <input type="submit" value="Detail" name="detail" class="detail"> 
    </form> 

創建使用相同的名稱與輸入字段的陣列不同索引 像名稱= '名稱[0]',名稱= '名稱[1]',名稱='名稱[ 2]」

後提交

<?php 



    if (isset($_POST['detail'])) { 
      session_start(); 
      echo $_POST['detailCart'][0]; 
      echo $_POST['detailCart'][1]; 
       echo $_POST['detailCart'][2]; 


     } 
    ?> 
+0

謝謝,但是,有沒有其他方式先生? –

+0

與評估或其他 –