John Davidson

php - Laravel - array to string with 2 fields

0 comments
Message:


$warehouses = [
{
"id": 1,
"name": "warehouse 1",
"pivot": {
"product_id": "1",
"warehouse_id": 1,
"qty": 136.5
}
},
{
"id": 2,
"name": "warehouse 2",
"pivot": {
"product_id": "1",
"warehouse_id": 2,
"qty": 71.5
}
}
]

I need result like below.


$result = ["warehouse 1 - 136.5", "warehouse 2 -  71.5"];

plz help



My Answer:
'id' => 1, 'name' => 'Warehouse A' },
{ 'id' => 2, 'name' => 'Warehouse B' },
{ 'id' => 3, 'name' => 'Warehouse C' }
];

$warehouseStrings = [];

foreach ($warehouses as $warehouse) {
$warehouseStrings[] = $warehouse['id'] . ' - ' . $warehouse['name'];
}

$warehouseString = implode(', ', $warehouseStrings);

echo $warehouseString; // Output: "1 - Warehouse A, 2 - Warehouse B, 3 - Warehouse C"

Rate this post

5 of 5 based on 4690 votes

Comments




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