'How to convert a associative array into a string using implode function
This is my associative array .
Array ( [month] => June [sale] => 98765 )
Array ( [month] => May [sale] => 45678 )
Array ( [month] => April [sale] => 213456 )
Array ( [month] => August [sale] => 23456 )
Array ( [month] => July [sale] => 12376 )
I want to convert it into two strings, like this
["June", "May", "April", "August", "july"]
and another one like this
[98765 , 45678 , 213456 , 23456 , 12376 ]
I have used Implode function but I think I am missing something. Can anybody please help ?
Solution 1:[1]
Simple,Use array_column():-
$month_array = array_column($array,'month');
$sale_array = array_column($array,'sale');
Output:- https://3v4l.org/ancBB
Note:- If you want them as strings then do like below:-
echo implode(',',array_column($array,'month'));
echo implode(',',array_column($array,'sale'));
Output:- https://3v4l.org/F17AP
Solution 2:[2]
You can look into the following code:-
$arr['month'] = array('June','July');
$arr['sale'] = array('123','234');
$strMonth = '["'.(implode('","', $arr['month'])).'"]';
$strSale = '['.(implode(', ', $arr['sale'])).']';
print_r($strMonth );
print_r($strSale );
And Output:-
["June","July"]
[123, 234]
Solution 3:[3]
You are effectively asking for array columns to be json_encoded.
To improve efficiency, use a foreach() to populate both arrays in one pass. This has half the time complexity of making two separate array_column() calls. I'll use a body-less loop with destructuring syntax for fun.
Code: (Demo)
$array = [
['month' => 'June', 'sale' => 98765],
['month' => 'May', 'sale' => 45678],
['month' => 'April', 'sale' => 213456],
['month' => 'August', 'sale' => 23456],
['month' => 'July', 'sale' => 12376],
];
$months = [];
$sales = [];
foreach ($array as ['month' => $months[], 'sale' => $sales[]]);
echo json_encode($months);
echo "\n---\n";
echo json_encode($sales);
Output:
["June","May","April","August","July"]
---
[98765,45678,213456,23456,12376]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Anant Kumar Singh |
| Solution 3 | mickmackusa |
