Home > Mobile >  Wordpress multi-dimentional array how to get the nested value without foreach loop
Wordpress multi-dimentional array how to get the nested value without foreach loop

Time:01-24

I got output from one of the WordPress table cells. The following value is displayed.

$allcoinkey=get_option('_transient_mcw-custom-data');
    var_dump($allcoinkey);

and the output:

 [0]=>
  array(2) {
    ["slug"]=>
    string(7) "bitcoin"
    ["keywords"]=>
    string(30) "بیتکوین,بیت کوین"
  }
  [1]=>
  array(2) {
    ["slug"]=>
    string(8) "ethereum"
    ["keywords"]=>
    string(27) "اتریوم,اتاریوم"
  }
}  

How do I access keyword values where slug=bitcoin without foreach?

CodePudding user response:

There are multiple ways to set this up.

For example, one way could be:

  1. Getting the 'slug' keys.
  2. And then searching through them using array_searchDocs function.
$multi_array = array(
        array(
            'slug'     => 'bitcoin',
            'keywords' => 'بیتکوین,بیت کوین'
        ),
        array(
            'slug'     => 'ethereum',
            'keywords' => 'اتریوم,اتاریوم'
        )
    );

$slugs_array = wp_list_pluck($multi_array, 'slug'); // Wordpress function
// OR
// $slugs_array = array_column($multi_array, 'slug'); // php function

echo array_search('bitcoin', $slugs_array) !== false
        ? $slugs_array[array_search('bitcoin', $slugs_array)]
        : 'SLUG NOT FOUND';

Which outputs this:

bitcoin

If the value doesn't exist like this:

echo array_search('zzz', $slugs_array) !== false
        ? $slugs_array[array_search('zzz', $slugs_array)]
        : 'SLUG NOT FOUND';

It'll output this:

SLUG NOT FOUND

CodePudding user response:

i use this sample code:

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>
  •  Tags:  
  • Related