Asked  1 Year ago    Answers:  5   Viewed   12 times

Say I have a multidimensional array in PHP such as:

this_array= array(
    string_name=>'string', 
    string_array=>array(
        'string_key'=>'string_val'
    )
)

How am I to access string_array's key-val pairs? Is it just:

this_array['string_array']['string_key'] 

Or is it something different?

 Answers

5

Code should look something like this, if you were intending on using strings as your keys.

$this_array= array(
     'string_name' => 'string', 
    'string_array' => array(
        'string_key' => 'string_val'
    )
);

Yes, you will access it by:

$this_array['string_array']['string_key'];
Saturday, May 29, 2021
 
Owen
 
2

I updated your function and it is giving expected output. Please give a try as following.

function array_key_exists_r($needle, $haystack){
    $result = array_key_exists($needle, $haystack);
    if ($result) 
    {
        foreach ($haystack as $a=>$v) 
        {
            if($needle == $a)
                return $haystack[$a];
            if (is_array($v)) {
                $result = array_key_exists_r($needle, $v);
            }
            if ($result) return $result;
        }
    }
    foreach ($haystack as $v) {
        if (is_array($v)) {
            $result = array_key_exists_r($needle, $v);
        }
        if ($result) return $result;
    }
    return $result;
};
Thursday, April 1, 2021
2
function searchMultiArray($val, $array) {
  foreach ($array as $element) {
    if ($element['key'] == $val) {
      return $element['field'];
    }
  }
  return null;
}

And then:

searchMultiArray(31, $myArray);

Should return "CONSTRUCTN".

Thursday, April 1, 2021
 
2

The actual problem is you're not assigning the result of array_reverse to anything

// change this
array_reverse($respArr);

// to this
$respArr = array_reverse($respArr);
Saturday, May 29, 2021
 
4

Nice choice of array_column()! Just extract an array with Country as the key and Out_Count as the value:

$los = 'Belgium';
$result = array_column($outs, 'Out_Count', 'Country')[$los];

To do it your way:

$los = 'Belgium';
$key = array_search($los, array_column($outs, 'Country'));
$result = $outs[$key]['Out_Count'];

Or:

$result = $outs[array_search($los, array_column($outs, 'Country'))]['Out_Count'];
Saturday, May 29, 2021
 
McAn
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :