PHP ARRAY获取特定值的项目索引

I have these 2 arrays $fonts['google'] and $data['value'] with the following content:

var_dump ($fonts['google']) outputs
array(4) {
    [0]=> array(3) { ["family"]=> string(7) "ABeeZee" ["variants"]=> array(2) { [0]=> string(7) "regular" [1]=> string(6) "italic" } ["subsets"]=> array(1) { [0]=> string(5) "latin" } } 
    [1]=> array(3) { ["family"]=> string(4) "Abel" ["variants"]=> array(1) { [0]=> string(7) "regular" } ["subsets"]=> array(1) { [0]=> string(5) "latin" } } 
    [2]=> array(3) { ["family"]=> string(13) "Abril Fatface" ["variants"]=> array(1) { [0]=> string(7) "regular" } ["subsets"]=> array(2) { [0]=> string(5) "latin" [1]=> string(9) "latin-ext" } } 
    [3]=> array(3) { ["family"]=> string(8) "Aclonica" ["variants"]=> array(1) { [0]=> string(7) "regular" } ["subsets"]=> array(1) { [0]=> string(5) "latin" } }
}


var_dump ($data['value']) outputs
array(4) {
    ["size"]=>  int(17) 
    ["family"]=>  string(3) "Exo"
    ["style"]=>  string(3) "200"
    ["subsets"]=>  string(5) "latin"
}       

Now I get the $data['value']['family'] = 'Abel' from my database.

Questions:

  • How can I get the ['variants'] for the given $data['value']['family'] value?
  • How can I get the index in $fonts['google'] for the sub-array where the $data['value']['family'] value is?

PHP supports Associative Arrays which let you use a (string) key rather than a numeric index for each element. These arrays are akin to javascript objects, Objective-C dictionaries, java HashMaps, etc. That makes scenarios like this easy. Do you have control over building the original data array? If you can refactor your storage, set up the arrays like this:

$fonts['google'] = [
    ["ABeeZee"] => [
        ["variants"]=>["regular", "italic"],
        ["subsets"]=>["latin"]
    ],
    ["Abel"] => [
        ["variants"]=>["regular"],
        ["subsets"]=>["latin"]
    ],
    ["Abril Fatface"] => [
        ["variants"]=>["regular"],
        ["subsets"]=>["latin", "latin-ext"]
    ],
    ["Aclonica"] => [
        ["variants"]=>["regular"],
        ["subsets"]=>["latin"]
    ]
]

extra credit: if you have the original data as in the post, you could convert it:

$newArray = array(); // or just [] in PHP >= 5.3 I believe
foreach($fonts['google'] as $index=>$fontArray) {
    $newArray[$fontArray['family']] = $fontArray;
    // this leaves a redundant copy of the family name in the subarray
    unset $newArray[$fontArray['family']]['family']; // if you want to remove the extra copy
}

Then it becomes trivial. Given a font family name, you just access $fonts['google'][$fontFamilyName] (or $newArray[$fontFamilyName]) using the family name as the array index.