PHP如何使用array_search和array_column保持匹配项的键?

时间:2016-09-12 03:52:04

标签: php arrays php-7

如何将匹配项目的密钥与array_searcharray_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'

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

你的array_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));
    }
}

http://sandbox.onlinephpfunctions.com/code/71934db55c67657f0336f84744e05097d00eda6d

答案 1 :(得分:1)

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

<?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) ); 

http://sandbox.onlinephpfunctions.com/code/83b306bfc30ef2a055cf49501bdeb5cb2e5b5ed7