从数据中获取信息的功能

时间:2014-10-19 22:33:11

标签: php

我有一些项目的信息:

其实我有这个阵列:

$datas = array(
    array(
        'name'            => "Banana", 
        'color'           => "yellow",
        'scientificName'  => "Banana",
        'weight'          => "300",
        'quantity'        => "3500",
        'origin'          => "Africa"
    ),
    array (...)
);

我需要像这样调用这个函数/数组:

示例1

// echo getDatas($what_I_know, "what_I_want");
// Must return yellow.
echo getDatas("Banana", "color");

示例2

// echo getDatas($what_I_know, "what_I_want");
// Must return 3500.
echo getDatas("yellow", "quantity");

所有密钥和数据都是唯一的。

问题

我该怎么办?

2 个答案:

答案 0 :(得分:0)

这是未经测试但应该有用。

foreach( $datas as $dat ) {
    foreach( $dat as $k => $d ) {
        if ( $what_i_know == $d ) {
            return $dat[$what_i_want];
        }
    }
}

答案 1 :(得分:0)

你可以使用这样的函数:

# parameters: $datas array, the value you've got, the value you want to find
function getData($datas, $got, $to_find) {
    foreach ($datas as $d) {
        # check if the value exists in the array
        if (array_search($got, $d)) {
            # it does! Make sure the property we want is also there
            if (in_array($to_find, array_keys($d))) {
                return $d[$to_find];
            }
            else {
                return "No value exists for $to_find";
            }
        }
    }
    return "No data found for $got.";
}


$datas = array(
    array(
        'name'            => "Banana", 
        'color'           => "yellow",
        'scientificName'  => "Banana",
        'weight'          => "300",
        'quantity'        => "3500",
        'origin'          => "Africa"
    ),
    array (
        'name'            => "Apple", 
        'color'           => "red",
        'scientificName'  => "Apple",
        'weight'          => "100",
        'quantity'        => "200",
        'origin'          => "England"

    )
);
echo getData($datas, "Banana", "color") . PHP_EOL;
echo getData($datas, "yellow", "quantity") . PHP_EOL;
echo getData($datas, "red", "weight") . PHP_EOL;
echo getData($datas, "Mongoose", "origin") . PHP_EOL;

输出:

yellow
3500
100
No data found for Mongoose.