如何使用内爆函数将关联数组转换为字符串

How to convert a associative array into a string using implode function

这是我的关联数组。

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 )

我想把它转换成两个字符串,像这样 ["June", "May", "April", "August", "july"]

还有一个像这样 [98765 , 45678 , 213456 , 23456 , 12376 ]

我使用了内爆函数,但我想我遗漏了一些东西。有人可以帮忙吗?

简单,使用array_column():-

$month_array = array_column($array,'month');
$sale_array = array_column($array,'sale');

输出:- https://3v4l.org/ancBB

注意:- 如果您希望将它们作为字符串,请执行以下操作:-

echo implode(',',array_column($array,'month'));

echo implode(',',array_column($array,'sale'));

输出:- https://3v4l.org/F17AP

您可以通过以下方式简单地做到这一点:

$strMonth = implode(', ', $arrVarName['month']);
$strSale = implode(', ', $arrVarName['sale']);

希望对您有所帮助!

你可以看看下面的代码:-

$arr['month'] = array('June','July'); 

$arr['sale'] = array('123','234'); 

$strMonth = '["'.(implode('","', $arr['month'])).'"]';


$strSale = '['.(implode(', ', $arr['sale'])).']';


print_r($strMonth );

print_r($strSale );

和输出:-

["June","July"]
[123, 234] 

您实际上要求数组列为 json_encoded。

为了提高效率,使用foreach()一次填充两个数组。这具有进行两个单独的 array_column() 调用的时间复杂度的一半。为了好玩,我将使用带有解构语法的 body-less 循环。

代码:(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);

输出:

["June","May","April","August","July"]
---
[98765,45678,213456,23456,12376]