简体   繁体   English

对foreach函数循环结果进行排序

[英]sorting a foreach function loop result

I have a MySQL query that gets the result of the entire MySQL database into a php array called $parents 我有一个MySQL查询,它将整个MySQL数据库的结果放入名为$parents的php数组中

then I have a foreach function loop that display result from that array 然后我有一个foreach函数循环,显示该数组的结果

the function: 功能:

 function subtree($id, $parents) { 
 if (isset($parents[$id]))
 foreach ($parents[$id] as $child) 
 {
 subtree($child, $parents);
 }
 } 

I need to sort the array result of this function, or to get the result into a new_sub_array then sort it and display result 我需要对该函数的数组结果进行排序,或者将结果放入new_sub_array然后new_sub_array进行排序并显示结果

any way to modify the function to do what i need? 任何方式修改功能来做我需要的吗?

Change your condition 改变你的状况

if (is_array($parents[$id]))

If Value is array then look for next sub tree 如果值是数组,则寻找下一个子树

else

otherwise write value. 否则写值。

If you want to sort an array - just use one of this function at the beginning of subtree() 如果要对数组进行排序-只需在subtree()的开头使用此函数之一

Good idea is to don't use recursion, instead of this you can use iteration and well prepared sql query instead of sorting in PHP ;) 好主意是不要使用递归,相反,您可以使用迭代和精心准备的sql查询,而不是在PHP中进行排序;)

Your function could look like this, I am not sure if I understand you, but it should be ok. 您的功能可能看起来像这样,我不确定是否了解您,但是应该没问题。

function subtree($parents) 
{
    if (is_array($parents))
    {
        sort($parents);
        foreach ($parents as $key => $value) 
        {
            subtree($value);
        }
    }
    else
    {
        echo $parents;
    }
} 

The $id argument is unnecessary. $ id参数是不必要的。

You'd sort the values when you call them from the database. 从数据库中调用它们时,可以对这些值进行排序。 So if you sorted them in descending order of date, for example: 因此,如果按日期的降序对它们进行排序,例如:

SELECT * FROM values WHERE :id=$id ORDER BY date DESC

Basically, ORDER BY is your friend. 基本上, ORDER BY是您的朋友。 This helped me a lot. 这对我很有帮助。

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

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