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

如何提取多维数组中name为transport_method[]的value值

如何从多维数组中提取指定name字段对应的value值?

Hey there! Let's tackle this problem step by step. You've got a multidimensional array where you need to pull out all the value entries where the name is exactly transport_method[] — here are a couple of straightforward ways to do that in PHP:

你的示例数组

$array = [
    ['name' => 'transport_method[]', 'value' => 'tran2'],
    ['name' => 'transport_method[]', 'value' => 'tran3'],
    ['name' => 'transport_method[]', 'value' => 'tran4'],
];

方法1:使用foreach循环(直观易读)

这是最适合新手理解的方式,我们遍历数组里的每一项,检查它的name是否匹配目标值,匹配的话就把对应的value收集到结果数组里:

$result = [];
foreach ($array as $item) {
    if ($item['name'] === 'transport_method[]') {
        $result[] = $item['value'];
    }
}

// 输出预期结果:Array ( [0] => tran2 [1] => tran3 [2] => tran4 )
print_r($result);

方法2:用array_filter + array_column(简洁函数式写法)

如果你喜欢用PHP内置的数组函数简化代码,可以先过滤出符合条件的数组元素,再一次性提取它们的value字段:

// 过滤出name为transport_method[]的元素
$filteredItems = array_filter($array, function($item) {
    return $item['name'] === 'transport_method[]';
});

// 提取过滤后元素的value字段
$result = array_column($filteredItems, 'value');

print_r($result);

两种方法最终都会得到你想要的结果:['tran2', 'tran3', 'tran4'],选你觉得顺手的方式就行!

内容的提问来源于stack exchange,提问作者Smritimay Debnath

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:56:16