Home > Backend Development > PHP Tutorial > 如何以数组中对象的某个字段为基准重新排列数组的内容

如何以数组中对象的某个字段为基准重新排列数组的内容

WBOY
Release: 2016-06-06 20:28:34
Original
1612 people have browsed it

比如下面是我从数据库中读取出来的数据,然后我想以suppliers_id为基准重新排列这个数组,有什么比较好的方法?

<code>[
    {
        cart_id: "6",
        suppliers_id: "1",
        goods_name: "商品1",
    },
    {
        cart_id: "7",
        suppliers_id: "1",
        goods_name: "商品2",
    }
    {
        cart_id: "7",
        suppliers_id: "1",
        goods_name: "商品3",
    }
]</code>
Copy after login
Copy after login

变成

<code>[
    //suppliers_id
    1:
    [
        {
            cart_id: "6",
            suppliers_id: "1",
            goods_name: "商品1",
        },
        {
            cart_id: "7",
            suppliers_id: "1",
            goods_name: "商品3",
        }
    ]
    //suppliers_id
    2:
    [
        {
            cart_id: "7",
            suppliers_id: "1",
            goods_name: "商品2",
        }
    ]
]</code>
Copy after login
Copy after login

回复内容:

比如下面是我从数据库中读取出来的数据,然后我想以suppliers_id为基准重新排列这个数组,有什么比较好的方法?

<code>[
    {
        cart_id: "6",
        suppliers_id: "1",
        goods_name: "商品1",
    },
    {
        cart_id: "7",
        suppliers_id: "1",
        goods_name: "商品2",
    }
    {
        cart_id: "7",
        suppliers_id: "1",
        goods_name: "商品3",
    }
]</code>
Copy after login
Copy after login

变成

<code>[
    //suppliers_id
    1:
    [
        {
            cart_id: "6",
            suppliers_id: "1",
            goods_name: "商品1",
        },
        {
            cart_id: "7",
            suppliers_id: "1",
            goods_name: "商品3",
        }
    ]
    //suppliers_id
    2:
    [
        {
            cart_id: "7",
            suppliers_id: "1",
            goods_name: "商品2",
        }
    ]
]</code>
Copy after login
Copy after login

看到标签是 php 表示无能为力。

如果是在前端处理你倒是可以用 sort(function(a,b){}) 这种思路来。

使用PHP的uksort函数,这货可以接收两个参数

<code>$arr = [
{c:"213"}
,
{c:"dadad"}]
function compare_func($a, $b){
    return $a=>c - $b=>c;
}
uksrot($arr,"compare_func" );</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template