Home > Backend Development > PHP Tutorial > 一个php数组转字符串的问题

一个php数组转字符串的问题

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:14:36
Original
1350 people have browsed it

怎样把以下这样的数组

<code>Array
(
    [0] => Array
        (
            [device_token] => Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu
        )

    [1] => Array
        (
            [device_token] => AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV
        )

)</code>
Copy after login
Copy after login

封装成

<code>"device_tokens":"device1,device2,…", 
这种形式
</code>
Copy after login
Copy after login

回复内容:

怎样把以下这样的数组

<code>Array
(
    [0] => Array
        (
            [device_token] => Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu
        )

    [1] => Array
        (
            [device_token] => AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV
        )

)</code>
Copy after login
Copy after login

封装成

<code>"device_tokens":"device1,device2,…", 
这种形式
</code>
Copy after login
Copy after login

$array = array(
    array(
        'device_token' => 'Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu'
    ),
    array(
        'device_token' => 'AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV'
    )
);
$result = [];
array_walk_recursive($array, function ($value, $key) use (&$result) {
    $result[$key][] = $value;
});
foreach ($result as $key => $value) {
    $result[$key] = implode($value, ',');
}
$result = json_encode($result);
// 如果你确定你不是想要json格式的话就保留下面
$result = substr($result, 1, -1);
Copy after login

//php5.5

$array = array(
    array(
        'device_token' => 'Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu'
    ),
    array(
        'device_token' => 'AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV'
    )
);
 //如果字段不固定的话参考楼上
$result = array_column($array,'device_token');
Copy after login

json_encode(array) JSON

<code>$out=['devices'=>''];
array_map(function($arr) use (&$out){
  $value=array_values($arr)[0];
  $out['devices'].=($out['devices'])?',':'';
  $out['devices'].=$value;
     
},$array);

print_r($out);</code>
Copy after login

Array
(

<code>[devices] => Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu,AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV</code>
Copy after login

)

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template