You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将二维数组指定列转换为扁平数组用于查询

二维数组转扁平字符串数组的解决方案

针对你给出的二维数组,这里提供几种实用的转换方法,最终得到目标数组 ["1","4","6","7","8"]:

方法一:PHP原生函数组合(推荐)

利用array_column提取指定字段,再通过array_map将数值转为字符串:

$originalArray = [
    ["location_id" => 1],
    ["location_id" => 4],
    ["location_id" => 6],
    ["location_id" => 7],
    ["location_id" => 8],
];

$flatArray = array_map('strval', array_column($originalArray, 'location_id'));

执行后$flatArray即为所需的扁平字符串数组。

方法二:foreach循环手动处理

适合需要更直观逻辑的场景:

$flatArray = [];
foreach ($originalArray as $item) {
    $flatArray[] = (string)$item['location_id'];
}

方法三:Laravel集合操作(适用于Laravel项目)

如果你的项目基于Laravel,可借助集合的链式操作快速实现:

use Illuminate\Support\Collection;

$collection = collect($originalArray);
$flatArray = $collection->pluck('location_id')->map(fn($id) => (string)$id)->toArray();

内容的提问来源于stack exchange,提问作者kinjal parmar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 10:21:12