Maison >développement back-end >tutoriel php >一个php数组转字符串的问题
怎样把以下这样的数组
<code>Array ( [0] => Array ( [device_token] => Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu ) [1] => Array ( [device_token] => AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV ) )</code>
封装成
<code>"device_tokens":"device1,device2,…", 这种形式 </code>
怎样把以下这样的数组
<code>Array ( [0] => Array ( [device_token] => Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu ) [1] => Array ( [device_token] => AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV ) )</code>
封装成
<code>"device_tokens":"device1,device2,…", 这种形式 </code>
<code class="php">$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);</code>
//php5.5
<code class="php">$array = array( array( 'device_token' => 'Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu' ), array( 'device_token' => 'AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV' ) ); //如果字段不固定的话参考楼上 $result = array_column($array,'device_token');</code>
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>
Array
(
<code>[devices] => Al9_G0i6ftf7fvkKsGM9o6jN5iyoqt8zTjcsh_kw6HUu,AmfUS3qeXKrJt1K1ZTICiD-ED6a_YgM3GdBRp6gR4RgV</code>
)