PHP二维数组如何据条件提取成一维?

$arr = [
            [
                "id" => 1,
                "view" => 2,
                'category_id' => 2,
                'title' => "标题一",
                "model" => 12,
                'desc' => "摘要",
            ],
            [
                "id" => 123,
                "view" => 2,
                'category_id' => 1,
                'title' => "标题二",
                "model" => 101,
                'desc' => "摘要",
            ]
        ];

我想取出id为 123 的数组,整个一维数组
希望可以传入一个id,以及下标, 就可以得到 下标的值

$title=getval(123,'title');

阅读 2.6k
5 个回答
<?php

$arr = [
    [
        "id" => 1,
        "view" => 2,
        'category_id' => 2,
        'title' => "标题一",
        "model" => 12,
        'desc' => "摘要",
    ],
    [
        "id" => 123,
        "view" => 2,
        'category_id' => 1,
        'title' => "标题二",
        "model" => 101,
        'desc' => "摘要",
    ]
];

function getVal($arr, $id, $key){
    foreach ($arr as $v){
        if($v['id'] == $id){
            return $v[$key];
        }
    }
}

$title = getVal($arr, 123, 'title');
var_dump($title);    // string(9) "标题二"

纯函数式解决方案

function getVal($arr,$id,$key){
        $result = array_filter($arr,function($item) use ($id){
            return $item["id"]==$id;
        });
        
        $result=reset($result);
        
        return $result[$key];
    }
    
    $name=getVal($arr,'1','title');

array_column

<?php
$arr = [

[
    "id" => 1,
    "view" => 2,
    'category_id' => 2,
    'title' => "标题一",
    "model" => 12,
    'desc' => "摘要",
],
[
    "id" => 123,
    "view" => 2,
    'category_id' => 1,
    'title' => "标题二",
    "model" => 101,
    'desc' => "摘要",
]

];

function getArrValueById($id,$arr){

$temp = array();
foreach ($arr as $item) {
    if ($item['id'] == $id ){
        $temp[] = $item;
        return $temp;
    }
}

}
echo '<pre>';
var_dump(getArrValueById(1,$arr));

array(1) {
[0]=>
array(6) {

["id"]=>
int(1)
["view"]=>
int(2)
["category_id"]=>
int(2)
["title"]=>
string(9) "标题一"
["model"]=>
int(12)
["desc"]=>
string(6) "摘要"

}
}

@仰望[myth6] 的是正解,但是他没有说出具体方法,只贴了个官方文档。

正解:

array_column($arr,'title','id')[123]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏