John Davidson

php - Create multidimensional array based on value

0 comments
Message:


I've spent hours trying to find the answer to this question, but I'm struggling. I'm reasonably familiar with PHP and the various in-built functions, and can build a complex foreach() loop to do this, but I thought I'd ask to see if anyone has a smarter solution to my problem.
I have an array in this form, Now I want to convert this into multidimensional based on list_id matched on next instance.I tried this solution but not worked well https://stackoverflow.com/a/65042103/4626270.
This may be duplicate but not got output here


<pre>Array
(
[0] => Array
(
[list_id] => 5
[order_list_name] => meri list 3
[0] => Array
(
[list_id] => 5
[product_id] => 1
[product_name] => DUCHESS WHITE WINE 200 ml
[sku] => SKU0001
[qty] => 2
)

)

[1] => Array
(
[list_id] => 5
[order_list_name] => meri list 3
[0] => Array
(
[list_id] => 5
[product_id] => 2
[product_name] => CONNEXION DOUBLE ROCK 350 ml, Pack of 2
[sku] => SKU0002
[qty] => 8
)

)

[2] => Array
(
[list_id] => 7
[order_list_name] => meri list 9
[0] => Array
(
[list_id] => 7
[product_id] => 2
[product_name] => CONNEXION DOUBLE ROCK 350 ml, Pack of 2
[sku] => SKU0002
[qty] => 2
)

)

)

I am expecting output like this


<pre>Array
(
[0] => Array
(
[list_id] => 5
[order_list_name] => meri list 3
[0] => Array
(
[list_id] => 5
[product_id] => 1
[product_name] => DUCHESS WHITE WINE 200 ml
[sku] => SKU0001
[qty] => 2
),
[1] => Array
(
[list_id] => 5
[product_id] => 1
[product_name] => DUCHESS WHITE WINE 200 ml
[sku] => SKU0001
[qty] => 2
)

)
[1] => Array
(
[list_id] => 7
[order_list_name] => meri list 9
[0] => Array
(
[list_id] => 7
[product_id] => 2
[product_name] => CONNEXION DOUBLE ROCK 350 ml, Pack of 2
[sku] => SKU0002
[qty] => 2
)

)

)


My Answer:
Here is a possible solution to create a multidimensional array based on the "list_id" value in PHP:

php
$data = [
["list_id" => 1, "name" => "John"],
["list_id" => 1, "name" => "Doe"],
["list_id" => 2, "name" => "Jane"],
["list_id" => 2, "name" => "Smith"],
["list_id" => 3, "name" => "Alice"],
["list_id" => 3, "name" => "Brown"]
];

$result = [];

foreach ($data as $item) {
$listId = $item['list_id'];

if (!isset($result[$listId])) {
$result[$listId] = [];
}

$result[$listId][] = $item;
}

print_r($result);


This code will create a multidimensional array where each key corresponds to a unique "list_id" value, and the value is an array of items with that "list_id".

Rate this post

3 of 5 based on 2291 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us