简体   繁体   English

更新和排序多维PHP数组

[英]Updating and Sorting a Multidimensional PHP Array

I have a mySQL query that dumps into an array, is sorted and then displayed, and that works perfectly. 我有一个mySQL查询,该查询转储到数组中,经过排序然后显示,并且运行良好。

My problem is that I want to update these values, re-sort them and display. 我的问题是我想更新这些值,对它们重新排序并显示。 I've been able to update the values, but it's within the same for loop and so it doesn't re-sort. 我已经能够更新这些值,但是它在相同的for循环内,因此不会重新排序。 So then I close the loop and re-sort but it doesn't save the updates I made in the first loop. 因此,我关闭了循环并重新排序,但是它没有保存我在第一个循环中所做的更新。 Help is much appreciated. 非常感谢您的帮助。

foreach ($arr as $mks){
if ($mks['Column1']==$Var) {$mks['Column2'] = $mks['Column2'] + 1;
}

My sorting code 我的排序代码

foreach ($arr as $mks){
    echo $mks['Column1'] . ", " . $mks['Column2'] . "<br>";
}

How do I get this to re-save into my array properly?! 我该如何将其正确保存到阵列中? I've tried googling this for most of the morning but has lead to frustration. 在整个上午的大部分时间里,我都尝试过使用谷歌搜索,但是却导致沮丧。

I think this is what you need: 我认为这是您需要的:

foreach ($arr as $key => $mks){
    if ($mks[$key] == $Var) {
        $arr[$key] = $mks+1;
    }
}

Now, $arr will contain the modified array, and you can use / modify it further as you need. 现在, $arr将包含修改后的数组,您可以根据需要进一步使用/修改它。

I don't see any "sorting code" but you can try to use references "&" instead of copy vars in your foreach(s) : 我没有看到任何“排序代码”,但是您可以尝试使用引用“&”代替在您的foreach中复制vars:

foreach($arr as & $mks){
...
}

Instead of copying your cells it will to give you a reference and every modifications done on it will be saved in the array. 除了复制您的单元格外,它还会为您提供参考,并且对其所做的所有修改都将保存在数组中。

Try changing your array like this instead 尝试像这样更改数组

foreach ($arr as $key => $mks){
    if ($mks['Column1']==$Var) {$arr[$key]['Column2'] = $mks['Column2'] + 1;
}

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

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