【发布时间】:2017-11-07 12:44:23
【问题描述】:
在我的代码中,我得到一个如下所示的数组
Array
(
[12247] => stdClass Object
(
[wid] => 12247
[uid] => 1626
[timestamp] => 1482021161
[weight_value] => 63.9
[nid] => 1195487
[source] => 0
[weight_entered] =>
)
[34843] => stdClass Object
(
[wid] => 34843
[uid] => 1632
[timestamp] => 1485298453
[weight_value] => 72.5
[nid] => 1206019
[source] => 8176
[weight_entered] =>
)
[35316] => stdClass Object
(
[wid] => 35316
[uid] => 1632
[timestamp] => 1485723529
[weight_value] => 54.2
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[35177] => stdClass Object
(
[wid] => 35177
[uid] => 1632
[timestamp] => 1485559176
[weight_value] => 53.3
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[12248] => stdClass Object
(
[wid] => 12248
[uid] => 1633
[timestamp] => 1481662016
[weight_value] => 56.6
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[12249] => stdClass Object
(
[wid] => 12249
[uid] => 1635
[timestamp] => 1479839680
[weight_value] => 54
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
)
数组按nid、timestamp、wid降序排列。我需要得到一个输出数组,它只包含最新的、第二个最新的和第一个权重值,并以 nid 作为索引。这样我就可以只获取特定 nid 的详细信息。
我想到的输出如下,其背后的逻辑是
这些多维数组有一个值
nid。我需要得到 最新、第二晚和第一个weight_value来自特定nid。由于数组已经按时间降序排序,我 只需要从每个内部获取第一个、第二个和最后一个值 数组有共同的nid
Array
(
[1195487] => stdClass Object
(
[latest_weight] => 63.9
[second_latest_weight] =>
[first_weight] =>
)
[1206019] => stdClass Object
(
[latest_weight] => 72.5
[second_latest_weight] =>
[first_weight] =>
)
[1209357] => stdClass Object
(
[latest_weight] => 54.2
[second_latest_weight] => 53.3
[first_weight] => 54
)
)
我尝试了代码,但由于没有得到正确的逻辑来应用,我陷入了困境。请帮忙。
我正在尝试的代码如下。但它并不完整,也不正确。
if(!empty($history_details)){
$last_weight = 0;
$second_last_weight = 0;
$first_weight = 0;
$prev_nid = '';
$prev_wid = '';
$prev_count = 1;
foreach($history_details as $single_history){
if(empty($weight_array[$single_history -> nid]['field_weight_format'])){
$current_weight = $weight_array[$single_history -> nid]['field_weight_value']." lbs";
}
else{
$current_weight = str_replace('-', ' ', $weight_array[$single_history -> nid]['field_weight_format']);
}
if($prev_nid == '' || $prev_nid != $single_history -> nid){
$last_weight = $single_history -> weight_value;
if($prev_nid != $single_history -> nid){
$prev_count = 1;
}
}
else if($prev_count === 2){
$second_last_weight = $single_history -> weight_value;
$first_weight = $single_history -> weight_value;
}
else if($prev_count > 2 && $prev_nid != $single_history -> nid){
$first_weight = $history_details[$prev_wid] -> weight_value;
}
$prev_count++;
$prev_nid = $single_history -> nid;
$prev_wid = $single_history -> wid;
}
}
【问题讨论】:
-
我正在尝试的代码如下。但它不完整,也不正确。 有什么问题?句法?逻辑?您得到的输出与您想要的不同(如果在此处发布)?
-
你的输出你想要什么不清楚。这背后的逻辑是什么?
-
@AlivetoDie,我已经编辑了问题并添加了逻辑。抱歉弄错了
-
I need to get the latest, second latest and the first weight_value from a particular nid-> 你说的是哪个nid。在输出数组中有三个nid -
@AlivetoDie,在给定的第一个数组中,它以 nid '1209357' 重复值四次。我需要获取这些子数组的最新、第二个和第一个 weight_value,并将它们与 nid 值作为索引