development

PHP-특정 문자열로 시작하는 배열에서 모든 키 가져 오기

big-blog 2020. 10. 25. 12:36
반응형

PHP-특정 문자열로 시작하는 배열에서 모든 키 가져 오기


다음과 같은 배열이 있습니다.

array(
  'abc' => 0,
  'foo-bcd' => 1,
  'foo-def' => 1,
  'foo-xyz' => 0,
  // ...
)

로 시작하는 요소 만 어떻게 얻을 수 foo-있습니까?


$arr_main_array = array('foo-test' => 123, 'other-test' => 456, 'foo-result' => 789);

foreach($arr_main_array as $key => $value){
    $exp_key = explode('-', $key);
    if($exp_key[0] == 'foo'){
         $arr_result[] = $value;
    }
}

if(isset($arr_result)){
    print_r($arr_result);
}

기능적 접근 :

http://php.net/array_filterarray_filter_key 의 주석에서 일종의 기능을 선택 하거나 직접 작성하십시오. 그런 다음 할 수 있습니다.

$array = array_filter_key($array, function($key) {
    return strpos($key, 'foo-') === 0;
});

절차 적 접근 :

$only_foo = array();
foreach ($array as $key => $value) {
    if (strpos($key, 'foo-') === 0) {
        $only_foo[$key] = $value;
    }
}

객체를 사용한 절차 적 접근 :

$i = new ArrayIterator($array);
$only_foo = array();
while ($i->valid()) {
    if (strpos($i->key(), 'foo-') === 0) {
        $only_foo[$i->key()] = $i->current();
    }
    $i->next();
}

당신이 얻은 가치로 무엇을하고 싶은지 이해하기 전에 더 효율적인 조언을 줄 수는 없지만 이렇게 할 것입니다.

$search = "foo-";
$search_length = strlen($search);
foreach ($array as $key => $value) {
    if (substr($key, 0, $search_length) == $search) {
        ...use the $value...
    }
}

PHP 5.3부터 다음 preg_filter함수를 사용할 수 있습니다 . 여기

$unprefixed_keys = preg_filter('/^foo-(.*)/', '$1', array_keys( $arr ));

// Result:
// $unprefixed_keys === array('bcd','def','xyz')

foreach($arr as $key => $value)
{
   if(preg_match('/^foo-/', $key))
   {
        // You can access $value or create a new array based off these values
   }
}

간단히 array_filter다음과 같이 솔루션을 달성하기 위해 기능을 사용했습니다.

<?php

$input = array(
    'abc' => 0,
    'foo-bcd' => 1,
    'foo-def' => 1,
    'foo-xyz' => 0,
);

$filtered = array_filter($input, function ($key) {
    return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY);

print_r($filtered);

산출

Array
(
    [foo-bcd] => 1
    [foo-def] => 1
    [foo-xyz] => 0
)

실시간 확인 https://3v4l.org/lJCse


Modification to erisco's Functional approach,

array_filter($signatureData[0]["foo-"], function($k) {
    return strpos($k, 'foo-abc') === 0;
}, ARRAY_FILTER_USE_KEY);

this worked for me.


In addition to @Suresh Velusamy's answer above (which needs at least PHP 5.6.0) you can use the following if you are on a prior version of PHP:

<?php

$input = array(
    'abc' => 0,
    'foo-bcd' => 1,
    'foo-def' => 1,
    'foo-xyz' => 0,
);

$filtered = array_filter(array_keys($input), function($key) {
    return strpos($key, 'foo-') === 0;
});

print_r($filtered);

/* Output:
Array
(
    [1] => foo-bcd
    [2] => foo-def
    [3] => foo-xyz
)
// the numerical array keys are the position in the original array!
*/

// if you want your array newly numbered just add:
$filtered = array_values($filtered);

print_r($filtered);

/* Output:
Array
(
    [0] => foo-bcd
    [1] => foo-def
    [2] => foo-xyz
)
*/

참고URL : https://stackoverflow.com/questions/4979238/php-get-all-keys-from-a-array-that-start-with-a-certain-string

반응형