php 通过特定键/属性索引数组/对象的集合。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 通过特定键/属性索引数组/对象的集合。相关的知识,希望对你有一定的参考价值。

<?php

/**
 * Index a collection of arrays/objects by a specific key/property.
 *
 * @param string $index
 * @param array $data
 * @return array
 */
function index_by( $index, array $data ) {
	$indexed_data = array();
	foreach( $data as $item ) {
		if( is_array( $item ) && array_key_exists( $index, $item ) ) {
			$indexed_data[$item[$index]] = $item;
		} else if( is_object( $item ) && property_exists( $item, $index ) ) {
			$indexed_data[$item->$index] = $item;
		}
	}
	return $indexed_data;
}

以上是关于php 通过特定键/属性索引数组/对象的集合。的主要内容,如果未能解决你的问题,请参考以下文章