PHP如何保持匹配项';带数组搜索和数组列的s键?

PHP如何保持匹配项';带数组搜索和数组列的s键?,php,arrays,php-7,Php,Arrays,Php 7,如何使用array\u search和array\u column保留匹配项的键 $items = array( 'meta-title' => [ "code" => 'meta-title' ], 'meta-keywords' => [ "code" => 'meta-keywords' ], ); $key = array_search('meta-title', array_column($it

如何使用
array\u search
array\u column
保留匹配项的键

$items = array(
    'meta-title' => [
        "code" => 'meta-title'
    ],

    'meta-keywords' => [
        "code" => 'meta-keywords'
    ],
);

$key = array_search('meta-title', array_column($items, 'code'));
var_dump($key); // 0
我追求的结果是:

'meta-title'
有什么想法吗?

您的
array\u columns()
调用返回一个数字索引的字符串数组(基于第一级的键),而不是要搜索的数组(即第二级的“code”值数组)。您最好遍历
$items
并在搜索要遍历的数组的基础上构建一个数组(键/值对):

$items = array(
    'meta-title' => [
        'code' => 'meta-title'
    ],

    'meta-keywords' => [
        'code' => 'meta-keywords'
    ],
);

$results = array();
foreach ($items as $key => $value) {
    $result = array_search('meta-title', $value);
    if ($result !== false) {
        array_push($results, array($key => $result));
    }
}

这是一种面向对象的方法,允许在运行时设置列和搜索值。作为一个类,它更具可重用性,并且有点自我文档化

<?php
$items = array(
    'meta-title' => [
        "code" => 'meta-title'
    ],

    'meta-keywords' => [
        "code" => 'meta-keywords'
    ],
);


/** 
 * Search all records of a recordset style array for a column containing a value
 * Capture the row into matches member for later use.  
 */
class ColumnSearch {

    private $key; 
    private $search;

    public $matches=array(); 

    public function __construct( $key, $search ){
        $this->key = $key;
        $this->search = $search;
    }

    public function search( array $items ){
        // @todo validate $items is like a recordset
        $matches = array_filter( $items, array( $this, "_filter"), ARRAY_FILTER_USE_BOTH );
        $this->matches = $matches; 
        return count($matches); 
    }

    private function _filter( $row, $rowKey ){ 
        return ( $row[$this->key] == $this->search ); 
    }
}

$search = new ColumnSearch( 'code', 'meta-title' ); 

$occurances = $search->search( $items ); 

// return value indicates how many were found, in case of multiples...
echo $occurances ." ". PHP_EOL;

// the matched row will be in matches member.  
var_dump($search->matches); 

// there might be more than 1, not in your example but this is very generic code.
// grab just the keys, then get the current 
echo current( array_keys($search->matches) ) . PHP_EOL;

echo "New Search for value that doesn't exist.". PHP_EOL; 
$newSearch = new ColumnSearch( 'code', 'title' ); 
$count = $newSearch->search( $items ); 
if( 0 == $count ){
    echo "Nothing found.". PHP_EOL; 
}
echo current( array_keys( $newSearch->matches) ); 

对不起,我弄错了。检查我的编辑上面。谢谢。你把它拆分成多个语句,然后在数组中使用
怎么样?1.获取所有第2列。使用_数组中的
检查列是否存在。如果
true
-你知道列名。你会怎么做?我已经解释了“算法”,谢谢你的想法。让我试试。