Home > Software engineering >  PHP 7 unconsisten multidimensional array get value
PHP 7 unconsisten multidimensional array get value

Time:05-01

As i said in the title i need a value from an array that begins with this text: text_1_en_

The arrays are numeric and the numbers change always so i cant just get the value by doing something like array[first][39][value].

Is there a function to search for that specific prefix and get the value ?

Following a sample array:

Array(
    [0] => Array (
        [lang] => de
        [value] => "text_1_en_Text i need"
        [id] => 2365
    )
    [1] => Array(
        [lang] => en
        [value] => "something i dont need"
        [id] => 2365
    )
)

What i want is to get the text after "text_1_en_". So my goal is to get "Text i need". Is there any "elegant" way to do this with PHP 7.4?

CodePudding user response:

I assume you the following array structure:

$plenty_variation['firstLevelKey'][0]['text_1_EN']  = "some English text";
$plenty_variation['firstLevelKey'][1]['text_2_EN']  = "some other English text";
$plenty_variation['firstLevelKey'][2]['does_not_start_with_text']  = "bla bla blup";

$plenty_variation['firstLevelKey2'][0]['text_1_EN']  = "L1K2 value of key starts with text";
$plenty_variation['firstLevelKey2'][1]['text_2_EN']  = "L1K2 another value of key starts with text";
$plenty_variation['firstLevelKey2'][2]['not_me']  = "L1K2 should not be matched";

$outputArray = [];
foreach($plenty_variation as $k => $subarray)
{
    foreach($subarray as $i => $numericIndexArray)
    {
        foreach($numericIndexArray as $key => $value)
        {
            if(preg_match("/^text/is", $key))
            {
                $outputArray[] = $value;
            }
        }
    }
}
print_r($outputArray);

This is the output:

enter image description here

CodePudding user response:

If you might be targeting more than one row, array_filter() is a wise functional choice.

Or if you know there will be only one qualifying row, then use a foreach() with an early break.

Code: (Demo)

$needle = 'text_1_en_';

var_export(
    array_filter(
        $array,
        fn($row) => str_starts_with($row['value'], $needle) 
    )
);

echo "\n---\n";

$result = [];
foreach ($array as $row) {
    if (str_starts_with($row['value'], $needle)) {
        $result = $row;
        break;
    }
}
var_export($result);

Output:

array (
  0 => 
  array (
    'lang' => 'de',
    'value' => 'text_1_en_Text i need',
    'id' => 2365,
  ),
)
---
array (
  'lang' => 'de',
  'value' => 'text_1_en_Text i need',
  'id' => 2365,
)
  • Related