简体   繁体   English

如何通过 user_id Laravel 更改数组结构

[英]How To change Array stucture by user_id Laravel

I have array structure like this:我有这样的数组结构:

[
  {product:"A", user_id:1},
  {product:"B", user_id:2},
  {product:"C", user_id:1}
]

I want re-structure array by user_id like this:我想通过 user_id 像这样重新构造数组:

[
  {user_id:1, product:["A","C"]},
  {user_id:2, product:["B"]}
]

How to change like that using php laravel, Thank you for your answer.如何使用 php laravel 进行更改,谢谢您的回答。

If I understand your question correctly, something like this would work:如果我正确理解你的问题,这样的事情会起作用:

NOTE: Im assuming your code is meant to describe an array of stdClass objects in php since what you've posted isnt valid php, if you really have an array of arrays, you'll need to adjust the syntax below to account for that.注意:我假设您的代码旨在描述 php 中的 stdClass 对象数组,因为您发布的内容不是有效的 php,如果您确实有一个数组数组,则需要调整下面的语法来解决这个问题。

<?php

$products = [
    (object) ['product' => "A", 'user_id' => 1],
    (object) ['product' => "B", 'user_id' => 2],
    (object) ['product' => "C", 'user_id' => 1]
];

$userProducts = [];
foreach ($products as $product) {

    // check if we have an object for this user id in our new array already 
    // and if so, just add this product to it
    $alreadyAdded = false;
    foreach ($userProducts as $userProduct) {
        if ($userProduct->user_id == $product->user_id) {
            $alreadyAdded = true;
            $userProduct->product[]= $product->product;
            break;
        }
    }

    // if no object for this user id in our new array yet, add one now
    if (!$alreadyAdded) {
        $newProduct = new \stdClass();
        $newProduct->user_id = $product->user_id;
        $newProduct->product = [$product->product];
        $userProducts[]= $newProduct;
    }
}

var_dump($userProducts);

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

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