[英]CakePHP - sort results array individually
Using CakePHP 2.7, I have an array of find results: 使用CakePHP 2.7,我有一系列查找结果:
array(
(int) 0 => array(
'Foo' => array(
'id' => '786',
'bar_id' => '12',
// more data
),
'Bar' => array(
'id' => '12',
// more data
)
),
(int) 1 => array(
'Foo' => array(
'id' => '785',
'bar_id' => '13',
// more data
),
'Bar' => array(
'id' => '13',
// more data
)
),
// many more results
Now I want do have it sorted by 'bar_id' in a defined individual way, not numeric . 现在,我想按定义的单独方式( 而不是数字)按“ bar_id”对它进行排序。 The sort order is described in another array:
排序顺序在另一个数组中描述:
array(9, 3, 18, 36, …)
Is there a better way to do it but to loop over the sort array, pick the current id then loop over the results array (a loop within a loop), look there for the corresponding 'bar_id' and if found write the result into a new results array? 有更好的方法吗?但是要遍历sort数组,选择当前id然后遍历result数组(循环内的一个循环),在其中查找对应的“ bar_id”,如果找到,则将结果写入新结果数组?
$results = array(…); // the results
$order = array(9, 3, 18, 36, …);
$sortedResults = array();
foreach ($order as $barId) {
foreach ($results as $result) {
if ($barId == $result['Foo']['bar_id']) {
$sortedResults[] = $result;
break;
}
}
}
I know that Cake has the Hash utility (formerly 'Set') to work with arrays, but I couldn't find a way to do it with Has. 我知道Cake可以使用Hash实用程序(以前称为“ Set”)来处理数组,但是我找不到使用Has进行处理的方法。
I would do this way: 我会这样:
$indexed_results = Hash::combine($results , '{n}.Foo.bar_id', '{n}');
foreach($order as $index)
{
$sortedResults[] = $indexed_results[$index];
}
the first row replaces the index in $results
with the corrispondant value of bar_id
so you can do a single loop 第一行替换索引
$results
用的corrispondant值bar_id
所以你可以做一个单循环
edit: probably you'll have to check that the $index
actually exists in your array unless you're sure that every value in $order
has a correspondent bar_id
otherwise you'll get a "Undefined index" notice 编辑:除非您确定
$order
中的每个值都具有对应的bar_id
否则可能必须检查$index
确实存在于数组中,否则会收到“未定义索引”通知
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.