简体   繁体   English

PHP:获取关联数组中的最后一个元素

[英]PHP: Getting last only element in associative array

I have a for loop . 我有一个for loop

$TOTAL_GOALS = 5;
for($i= 1; $i<=$TOTAL_GOALS; $i++) {
    $EACH_POST_QUERY = mysql_query("SELECT item_id FROM likes WHERE item_id='$i'");
    $EACH_POST_TOTAL_LIKES = mysql_num_rows($EACH_POST_QUERY);
    $EACH_POST_RESULT = array();
    $EACH_POST_RESULT[$i] = $EACH_POST_TOTAL_LIKES;
}

In the loop, I'm dynamically firing queries and fetching result into a variable called $EACH_POST_TOTAL_LIKES . 在循环中,我将动态触发查询并将结果提取到名为$EACH_POST_TOTAL_LIKES的变量中。

I want to make an associative array based on this. 我想基于此创建一个关联数组。 So, I have created an array called $EACH_POST_RESULT = array(); 因此,我创建了一个名为$EACH_POST_RESULT = array(); and pushing value into it. 并将价值推向其中。

The output I'm getting is the last element - example: 我得到的输出是最后一个元素-示例:

3:16

My expected output is - 我的预期输出是-

1:12 2:14 3:16

I'm sending result to JS using this - 我正在使用此将结果发送到JS-

$SERVER_DATA = array("TG"=>$TOTAL_GOALS, "EACH_POST_LIKES"=> $EACH_POST_RESULT);
echo json_encode($SERVER_DATA);

Console is showing me only last entry. 控制台仅向我显示最后一个条目。 Why does array overwriting values and storing last one? 为什么数组覆盖值并存储最后一个?

What is missing? 什么东西少了?

You are creating array every time in the loop. 您每次在循环中都要创建array I would suggest you to implement this in single query using MySQL Between Clause if you want to get count of all parameters once. 如果您想一次获取所有参数的计数,我建议您使用MySQL Between Clause在单个查询中实现。

Try this: 尝试这个:

 $TOTAL_GOALS = 5; $EACH_POST_RESULT = array(); for ($i = 1; $i <= $TOTAL_GOALS; $i++) { $EACH_POST_QUERY = mysql_query("SELECT item_id FROM likes WHERE item_id='$i'"); $EACH_POST_TOTAL_LIKES = mysql_num_rows($EACH_POST_QUERY); array_push($EACH_POST_RESULT, $EACH_POST_TOTAL_LIKES); } 

You need to move this line before the loop: 您需要在循环之前将以下行移动:

$EACH_POST_RESULT = array();

Otherwise it will be replaced with an empty array each time! 否则每次都会被一个空数组替换!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM