簡體   English   中英

PHP關聯數組,僅包含1個元素

[英]PHP associative array with only 1 element

我有一個返回數組的函數(結果來自bd)

$resultat = $bd->Select($sql);

forarray結果在數組中,如果它們不符合要求,我將其從數組中刪除。

foreach($indexToRemove as $elem)
    unset($resultat[$elem]);

然后,我將數組放入會話數組

$_SESSION['entrepriseTrouver'] = $resultat;

然后,我將結果顯示到頁面中

        $nbResultatParPage = 9; // Correspond au nombre de résultats maximale désirés par page
        $index = (($nbResultatParPage*($_SESSION['page'] - 1)) + 1); // Trouve l'index actuel à afficher ( le nombre de résultats par page * le chiffre de la page précédente ) + 1
        $max = $index + $nbResultatParPage; // Correspond a l'index maximum à afficher


        for($index; $index < $max; $index++) // On affiche les entreprises
        {
            echo "<br/>";
            if(isset($_SESSION['entrepriseTrouver'][$index-1]))
            {
                echo "#".$index."<br/>";
                print_r($_SESSION['entrepriseTrouver'][$index-1]);
                echo "<br/>";
                //echo $_SESSION['entrepriseTrouver'][$index-1][3]."<br/>".$_SESSION['entrepriseTrouver'][$index-1][7]."<br/><br/>";
                echo "-------------------------------------------------------------------------------------------------------------------------------";
            }

        }

當我的數組中沒有元素或不超過1個元素時,一切工作正常,但是當我只有1個元素時,無法使用索引0訪問它

print_r($_SESSION['entrepriseTrouver'][0]);

我只能使用密鑰訪問它。 例如,我的BD返回20個元素,並且取消設置除#17之外的所有元素,因此我將必須以這種方式訪問​​它

print_r($_SESSION['entrepriseTrouver'][17]);

我不明白為什么當數組中只有1個元素時無法使用索引0訪問數組。

取消設置數組中的值不會重新為其編制索引。 因此,剩下的數組的索引值為17。

使用array_values修復此問題。

foreach($indexToRemove as $elem){
    unset($resultat[$elem]);
}
$_SESSION['entrepriseTrouver'] = array_values($resultat);

print_r($_SESSION['entrepriseTrouver'][0]);

取消設置數組元素時,將刪除該元素及其鍵。 因此,如果刪除鍵17上的項目以外的所有項目,則您的一項是鍵17,而鍵0不存在。

一種快速解決方案是將結果分配給會話時對結果運行array_values

$_SESSION['entrepriseTrouver'] = array_values($resultat);

這將返回數組中的所有值並以數字方式進行索引,從而具有重新索引數組的作用。 如果數組中只有一項,那么它將位於鍵0。

unset()不會重置陣列鍵。 您可以通過執行以下操作來重置陣列鍵,這會將鍵重置為從0開始遞增的數字

$_SESSION['entrepriseTrouver'] = array_values($_SESSION['entrepriseTrouver']);

當您從數組中刪除元素時,PHP不會重置您的數組。 僅僅因為數組中只有一個元素並不意味着它就是元素0。示例:

$x[] = "foo"

echo $x[0] // echos "foo"

$x[0] = "foo"
$x[1] = "bar"
unset($x[0])
echo $x[0] // echos nothing
echo $x[1] // echos "bar"

如果將$ x [5]設置為“ foo”,則不會期望$ x [0]為“ foo”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM