【问题标题】:How to sort array with condition using loop in php如何在php中使用循环对数组进行排序
【发布时间】:2021-09-24 07:09:11
【问题描述】:

我正在使用 codeigniter,我想将记录获取为“两个数组” 基于条件(FilterType='Tag',FilterType='Merchant')

这是我的表“filterproducts”

id          FilterType          CategoryUrl
1           Tag                 abc
2           Tag                 xyz
3           Merchant            abc
4           Merchant            abc

这是我当前的代码,它给了我多维数组

function SearctRecords()
 {
        $this->db->select("*")
            ->from("filterproducts  fp")
            ->join("filterid fi", "fp.FilterType=fi.name")
            ->where("fp.CategoryUrl", $CategoryUrl);
            $query = $this->db->get();  
            $result = $query->result_array();
            return $result;
}

这是我的控制器

function SearchFilterProducts()
{
        $users['data'] = $this->Customer_model->SearctRecords($CategoryUrl);
        $responseJSON = array("Status" => $status, "data" => $users['data']);
             header("content-type:application/json");
             $response = json_encode($responseJSON);
             echo $response;
}

【问题讨论】:

  • 你能发布你预期的数组结果吗?

标签: php arrays codeigniter


【解决方案1】:

我建议使用现有的数据库排序方法进行排序。通常会比自定义 PHP 函数执行得更好。

如果您仍想对多维结果进行排序,请考虑使用 usort。

function custom_super_comparator($a, $b) {
    //custom comparison
}

usort($response, "custom_super_comparator");

检查这个主题的好答案: Sort array of objects by object fields

题外话,SearctRecords 缺少参数

SearctRecords($CategoryUrl) {

【讨论】:

    猜你喜欢
    • 2015-11-05
    • 2017-08-26
    • 2011-09-30
    • 1970-01-01
    • 2021-05-07
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多