douliu7929 2016-02-09 17:02
浏览 27
已采纳

PHP - 更新以前的cookie以形成数组

I have the following code:-

<?php 

if(!is_user_logged_in()) {
    $fav_cookie = array($_GET['job_fav']);
    $cookie_url = '/jobs/?job_fav=<?php the_ID(); ?>';

    if($job_fav !='') {
         setcookie(COOKIE_PREFIX . "job_fav",    " ", time() - 3600);
         setcookie(COOKIE_PREFIX . "job_fav", array($fav_cookie));
         header("Location: $cookie_url");
    }
?>

<a href="/jobs/?job_fav=<?php the_ID(); ?>">
    <div class="job-single-favourite icon-<?php echo $job_sector_html; ?>
        <?php if (in_array(get_the_ID(), $fav_cookie)) {
                  echo ' starred-job';
              }
        ?>">
    </div>
</a><!-- none-logged-in starred-job -->

<?php } ?>

This is working fine, but it is only storing one value as a cookie at a time.

Basically what I am wanting to do is on click of the favourite icon it needs to store the job ID within the $fav_cookie array.

What is happening at the moment is that if you favourite a job $fav_cookie is being replaced by the new job ID. I somehow want to add each cookie inside the $fav_cookie array so it would become 113, 120, 234 for example, instead of replacing the ID each time.

If I haven't explained what I am wanting to achieve in great enough detail, let me know and I will amend my post.

EDIT:--

Just to add, the following works:-

$jobID = get_the_ID();
$jobListing = array(get_the_ID());
$html = '';
//$currentIDs = explode('|', $_COOKIE[COOKIE_PREFIX . 'job_fav']);
$currentIDs = array('493','311');

var_dump($currentIDs);
foreach ($jobListing as $job) {

    $customClass = (in_array($jobID, $currentIDs)) ? ' starred-job' : '';

   // $html = '';
    $html .= '<a href="/jobs/?job_fav=' . htmlspecialchars($jobID) . '">';
    $html .= '<div class="job-single-favourite icon-' . htmlspecialchars($job_sector_html) . $customClass . '">';
    $html .= '</div></a>';
}


echo $html;

All I need now is $currentIDs to display be an array of the favourite jobs defined from $_COOKIE and it should be done.

$currentIDs = explode('|', $_COOKIE[COOKIE_PREFIX . 'job_fav']); is an empty array

EDIT 2

Okay I now have the following:-

$jobID = get_the_ID();
$jobListing = array(get_the_ID());

$favourite_cookie = array($_GET['job_fav']);
$ids_string = implode('|', $favourite_cookie);
setcookie('job_fav', $ids_string);

var_dump($_COOKIE['job_fav']);


$ids_string = $_COOKIE['job_fav'];
$ids = explode('|', $_COOKIE['job_fav']);
<?php 
if (!is_user_logged_in()) {

$jobID = get_the_ID();
$jobListing = array(get_the_ID());
$html = '';
$currentIDs = explode('|', $_COOKIE[COOKIE_PREFIX . 'job_fav']);
$currentIDs = $ids;

foreach ($jobListing as $job) {

    $customClass = (in_array($jobID, $currentIDs)) ? ' starred-job' : '';

    $html = '';
    $html .= '<a href="/jobs/?job_fav=' . htmlspecialchars($jobID) . '">';
    $html .= '<div class="job-single-favourite icon-' . htmlspecialchars($job_sector_html) . $customClass . '">';
    $html .= '</div></a>';
}


echo $html;

} ?>

And now have two issues:-

  • When I favourite a job, I have to click twice in order for it to update.
  • $_COOKIE['job_fav'] gets replaced with the new job ID every time you favourite a different job, instead of adding it to the array
  • 写回答

2条回答 默认 最新

  • douzhoulei8959 2016-02-11 17:26
    关注

    You could use implode and explode when creating/retrieving the $_COOKIE.

    So for example when you want to create/update the list of IDs within the $_COOKIE you would first explode the current $_COOKIE if set.

    if (isset($_COOKIE[COOKIE_PREFIX . 'job_fav'])) {
        $jobIDs   = explode('|', $_COOKIE[COOKIE_PREFIX . 'job_fav']);
        $jobIDs[] = $_GET['job_fav']; // Add new ID to the list.
    
        // We store them as a string, that we can explode when needed.
        setcookie(COOKIE_PREFIX . "job_fav", implode('|', $jobIDs)); 
    }
    

    If you ever want to turn the $_COOKIE into the array format, you just do:

    explode('|', $_COOKIE['job_fav']);

    I believe that you give you a good idea of how you can store it. Any questions, just let me know.

    Edit: I had a few spare minutes, I tried to implement it/clean up your code a little. Not sure if I got it all right but it's at least something for you to work off:

    if (!is_user_logged_in()) {
    
        $id          = the_ID();
        $favouriteID = $_GET['job_fav'];
        $cookieURL   = '/jobs/?job_fav=' . $id;
    
        $currentIDs  = []; // Storage Array.
    
        // If the user has the $_COOKIE set already.
        if (isset($_COOKIE[COOKIE_PREFIX . 'job_fav'])) {
            $currentIDs = explode('|', $_COOKIE[COOKIE_PREFIX . 'job_fav']);
    
            // Append the new ID.
            $currentIDs[] = $favouriteID;
            setcookie(COOKIE_PREFIX . 'job_fav', implode('|', $currentIDs));
            header('Location: ' . $cookieURL);
            exit;
        }
    
        $currentIDs[] = $favouriteID;
        setcookie(COOKIE_PREFIX . 'job_fav', implode('|', $currentIDs));
    
        // Build up the HTML.
        $html  = '';
        $html .= '<a href="/jobs/?job_fav=' . htmlspecialchars($id) . '">';
        $html .= '<div class="job-single-favourite icon-' . htmlspecialchars($job_sector_html);
        if (in_array($id, $currentIDs)) {
            $html .= ' starred-job';
        }
        $html .= '">';
        $html .= '</div></a>';
    
        echo $html;
    }
    

    Can see it here: https://ideone.com/ivxRAT

    There are multiple other ways to clean up the above, but without knowing your code base and what the get_ID() and get_the_ID() functions are doing it's hard for me to do it. Really if these are just returning the same ID for each instance each time, you may as well call it once at the top, store it in a variable and use that when query whether the ID exists in the array, etc.

    Edit2: No idea why your code isn't working, the logic works fine for me, it will now store multiple $_COOKIES as shown in the ideone.

    So I can only presume that your problem is how you're then using your $_COOKIE to decide whether you need to apply the styles or not.

    So since I have no idea about how you are doing this, I can only guess.

    I'm guessing somewhere you have a database query that pulls out all your current jobs. I'm also guessing that you loop through that data to print them out to the page. So here is what I would suggest:

    $jobListing = <PULLDATAFROMDATABASE>
    
    $html = '';
    $currentIDs = explode('|', $_COOKIE[COOKIE_PREFIX . 'job_fav']);
    foreach ($jobListing as $job) {
    
        $customClass = (in_array($job->id, $currentIDs)) ? ' starred-job' : '';
    
        $html .= '<a href="/jobs/?job_fav=' . htmlspecialchars($id) . '">';
        $html .= '<div class="job-single-favourite icon-' . htmlspecialchars($job_sector_html) . $customClass . '">';
        $html .= '</div></a>';
    }
    
    echo $html
    

    Edit3:

    How to set the cookies:

    $ids = array(1,2,3,4);
    $ids_string = implode('|', $ids);
    setcookie('job_fav', $ids_string);
    

    How to get the cookies:

    $ids_string = $_COOKIE['job_fav'];
    $ids = explode('|', $_COOKIE['job_fav']);
    

    So if we do: print_r($ids);

    We get:

    Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

    Edit3:

    The first part.

    $jobID        = get_the_ID();
    $jobListing   = array(get_the_ID());
    $favouriteIDs = array();
    
    $favourite_cookie = $_GET['job_fav']; // This is the new id we want to add to the array?
    if (isset($_COOKIE['job_fav'])) {
        $favouriteIDs = explode('|', $_COOKIE['job_fav']);
    }
    $favouriteIDs[] = $_GET['job_fav']; // Append the new ID onto the array.
    setcookie('job_fav', implode('|', $favouriteIDs));
    
    var_dump($_COOKIE['job_fav']);
    

    The other part

    if (!is_user_logged_in()) {
    
        $jobID        = get_the_ID();
        $jobListing   = array(get_the_ID());
        $html         = '';
        $favouriteIDs = explode('|', $_COOKIE['job_fav']);
    
        foreach ($jobListing as $job) {
    
            $customClass = (in_array($jobID, $favouriteIDs)) ? ' starred-job' : '';
    
            $html = '';
            $html .= '<a href="/jobs/?job_fav=' . htmlspecialchars($jobID) . '">';
            $html .= '<div class="job-single-favourite icon-' . htmlspecialchars($job_sector_html) . $customClass . '">';
            $html .= '</div></a>';
        }
    
        echo $html;
    }
    

    Don't know if there's something strange going on in your code, but you randomly added Opening/Closing PHP tags. If they need to be there for some reason and this isn't the full code following on from one another, you can add them back in.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮