内爆()一个二维数组最简单的方法? [英] Easiest way to implode() a two-dimensional array?

查看:172
本文介绍了内爆()一个二维数组最简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的PHP,并没有关于它的工作原理相当的抓地力。如果我有一个二维阵列本身(由数据库返回):

I'm new to PHP, and don't have quite the grip on how it works. If I have a two dimensional array as such (returned by a database):

array(3) {   
    [0]=> array(1) {         
        ["tag_id"]=> string(1) "5" 
    } 
    [1]=> array(1) {         
        ["tag_id"]=> string(1) "3" 
    } 
    [2]=> array(1) {         
        ["tag_id"]=> string(1) "4" 
    } 
}

和希望把它变成字符串 5,3,4 什么是不这样做的最快方法?我现在有一个讨厌的的foreach 循环,但希望它可以在同一行来完成。一个标准的破灭给我数组,数组,数组

and want to turn it into the string 5,3,4 what would be the quickest way do do this? I currently have an obnoxious foreach loop, but was hoping it could be done in one line. A standard implode gives me Array,Array,Array.

推荐答案

本使用修改阵列 array_map ,但可能为将其变成 TAG_ID 的的一维数组更好。然后,你可以使用破灭像正常的:

This modifies your array using array_map, but probably for the better by turning it into a 1D array of tag_id's. Then you can just use implode like normal:

$arr = array_map(function($el){ return $el['tag_id']; }, $arr);
$str = implode(',', $arr);

如果你不想修改阵列比你可以这样做:

If you don't want to modify your array than you can just do this:

$str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));

codePAD演示

这篇关于内爆()一个二维数组最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆