2016-08-22 113 views
-3

朋友我是新的PHP。我正在玩數組。所以我無法解決使用數組的一個登錄。在這個程序中,我想顯示數組限制。我有一些數據來自數據庫。但我想顯示限制數據(僅限10個帖子)。我知道MYSQL查詢顯示限制數據。但我想用數組。所以請幫忙解決這個邏輯謝謝。PHP數組限制?

這裏是代碼。

$reverse = array_reverse($showpost, true); 

foreach ($reverse as $key=>$postvalue) { 
    $latestpost = explode(',', $postvalue['postcategory']); 

    if (in_array("3", $latestpost)) { 
     // result here... 

    } 

} 

我已經保存類別這種格式(1,2,3,4,5,6)。這就是我使用explode()函數的原因。 我的數據庫字段名稱是(post_id,postname,postcategory,postdisc)。

回答

1

不知道如果我理解正確的問題,但我認爲這可能與this link

$input = array("a", "b", "c", "d", "e"); 
$output = array_slice($input, 0, 3); // returns "a", "b", and "c" 
+0

但如何證明使用該功能的數據。因爲$ output ['postname']不起作用。 –

0

可以使用array_chunk()功能

CODE:

<?php 
$reverse = array_reverse($showpost, true); 

foreach($reverse as $key=>$postvalue){ 
    $latestpost = explode(',', $postvalue['postcategory']); 
    $chunks = array_chunk($latestpost, 3); 
    print_r($chunks); 
} 
?> 
+0

但如何顯示數據我使用$ chunks ['postnane']此方法不起作用。 –

+0

$ chunks是3值對中的數組只是使用foreach循環或索引,如果你想打印第一對然後使用$ chunks [0]爲下一個數組只是增加索引1,2,像這樣 – Sateesh

0

如果」只想顯示10行,而result here...是每個帖子顯示的位置,然後像這樣的東西可能會工作:

$postsShown = 0; 
$reverse = array_reverse($showpost, true); 

foreach ($reverse as $key => $postvalue) { 

    if ($postsShown >= 10) { 
     break; 
    } 

    $latestpost = explode(',', $postvalue['postcategory']); 

    if (in_array("3", $latestpost)) { 

     // result here... 

     $postsShown++; 
    } 
} 

所有這些都會計算使用$postsShown變量顯示多少帖子,並在顯示新帖子時遞增。當這個變量達到10(IE,顯示10個帖子)時,循環將使用break命令終止。

+0

抱歉你的邏輯不工作。 .. –

0

也許你可以使用會話變量來保存用戶用來記錄的幾次嘗試,然後在服務器中進行驗證。

與此代碼,你可以創建一個會話變量:

session_start(); 
$_SESSION['name_of_my_variable'] = 'value of my session variable'; 

和例如每個用戶嘗試登錄,你可以增加你的櫃檯在會話變量中的值時:

第一時間您需要創建會話變量:

session_start(); 
$_SESSION['log_counter'] = 1; 

,你增加計數器這樣的下一個嘗試:

session_start(); 
$log_counter = $_SESSION['log_counter']; 
$log_counter++; 
$_SESSION['log_counter'] = $log_counter; 

檢查,如果用戶已經達到了極限:

session_start(); 
if ($_SESSION['log_counter'] == 10) 
{ 
    echo "Limit reached"; 
} 

這是最後的代碼

// init session variables 
session_start(); 

// Check if exist the session variable 
if (isset($_SESSION['log_counter'])) 
{ 
    // Enter here if the session variable exist 

    // check if the log_counter is equals to the limit 
    if ($_SESSION['log_counter'] == 10) 
    { 
     echo "Limit reached"; 
    }else 
    { 
     // increase the counter 
     $log_counter = $_SESSION['log_counter']; 
     // this increate 1 more to the log_counter session variable 
     $log_counter++; 
     // here we save the new log_counter value 
     $_SESSION['log_counter'] = $log_counter; 
    } 
}else 
{ 
    // Enter here if not exist the session variable 

    // this create the log_counter session variable 
    $_SESSION['log_counter'] = 1; 
}