基于列表php提取选定的数组值

时间:2017-12-16 10:36:23

标签: php arrays extract partial

我有一个字符串形式的数组键列表

"hasAddStrict,freqItems,freqAmount,freqUnit,freqFirstDayOfWeek"

现在,想要只提取那些值,即$ myarray [' hasAddstrict']应该变成$ hasAddStrict等。

有一个简短的方法吗?我相当肮脏的解决方案:

$ff = explode(',' ,"hasAddStrict,freqItems,freqAmount,freqUnit,freqFirstDayOfWeek");
    foreach ( $ff   as $key){   $ff[$key] =    $SERVICE[$key]  ;    }
    extract($ff);

1 个答案:

答案 0 :(得分:0)

我同意杰夫认为没有更好的方法,并且将变量保持为数组可能是一个更好的主意,但你可以将它包装在一个函数中以方便(在php 5.6中测试):< / p>

<?php

function array_extract(array $assoc_array, $keys_list)
{
    return array_intersect_key($assoc_array, array_flip(explode(',', $keys_list)));
}

extract(array_extract($SERVICE, "hasAddStrict,freqItems,freqAmount,freqUnit,freqFirstDayOfWeek"));

按以下方式进行测试时:

$SERVICE = [
    'hasAddStrict' => 123,
    'freqItems' => 456,
    'freqAmount' => 789,
    'freqUnit' => 'abc',
    'freqFirstDayOfWeek' => 'def',
];

extract(array_extract($SERVICE, "hasAddStrict,freqItems,freqAmount,freqUnit,freqFirstDayOfWeek"));

var_dump($hasAddStrict, $freqItems, $freqAmount, $freqUnit, $freqFirstDayOfWeek);

你得到输出:

int(123)
int(456)
int(789)
string(3) "abc"
string(3) "def"