0

I am trying to get a specific value out of a deeply nested PHP array. I have gotten as far as reaching reaching the array that I need and storing it in a variable. The array looks like this:

Array ( 
    [0] => Array ( 
        [social_channel] => twitter
        [link] => testing@twitter.com
    )
    [1] => Array (
        [social_channel] => mail
        [link] => hcrosby@testing.edu 
    )
)

Often times this array will contain numerous values such as facebook links, twitter, instagram and they will always be in different orders based on how the user inputs them. How do I only pull out the email address in this array. I know this is basic but PHP is far from my strong point.

xkcd149
  • 842
  • 1
  • 11
  • 17
JordanBarber
  • 2,041
  • 5
  • 34
  • 62
  • 1
    Possible duplicate of [PHP multi dimensional array search](http://stackoverflow.com/questions/6661530/php-multi-dimensional-array-search) – Jay Blanchard Jan 25 '16 at 16:26

5 Answers5

1

Assuming you've got the following:

$my_array = [
    ['social_channel' => 'twitter', 'link' => 'testing@twitter.com'],
    ['social_channel' => 'mail', 'link' => 'hcrosby@testing.edu'],
];

You'd could loop over each item of the array using a foreach and then use the link array key to get the email address. For example:

foreach ($my_array as $item) {
    echo $item['link']; // Or save the item to another array etc.
}
Grant J
  • 1,056
  • 3
  • 10
  • 18
1

You can use array_map function

$my_array = [
['social_channel' => 'twitter', 'link' => 'testing@twitter.com'],
['social_channel' => 'mail', 'link' => 'hcrosby@testing.edu'],
];

function getMailArray($array) {
  return $array['link'];
}

$result = array_map("getMailArray",$my_array);
Naumov
  • 1,167
  • 9
  • 22
0

Try this:

$arr1 = array(array('social_channel' => 'twitter', 'link' =>    'testing@twitter.com'),
             array('social_channel' =>  'mail', 'link' =>   'hcrosby@testing.edu'));
$emailArr = array();
foreach ($arr1 AS $arr) {
    $emailArr[] = $arr['link'];
}
print_r($emailArr);
Sanjay Kumar N S
  • 4,653
  • 4
  • 23
  • 38
0
$assoc = [];
foreach($array as $sub){
    $assoc[$sub["social_channel"]] = $assoc["link"];
}

The above changes social_channel into a key so that you can search directly like this:

$email = $assoc["email"];

Remember to ensure that the input contains the email field, just to avoid your error.log unnecessarily spammed.

SOFe
  • 7,867
  • 4
  • 33
  • 61
0
<?php

    function retrieveValueFromNestedList(array $nestedList, $expectedKey)
    {
        $result = null;
        foreach($nestedList as $key => $value) {
            if($key === $expectedKey) {
                $result = $value;
                break;
            } elseif (is_array($value)){
                $result = $this->retrieveValueFromNestedList($value, $expectedKey);
                if($result) {
                    break;
                }
            }    
        } 
    }