JordanBarber
JordanBarber

Reputation: 2101

Obtain specific piece of PHP array?

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] => [email protected]
    )
    [1] => Array (
        [social_channel] => mail
        [link] => [email protected] 
    )
)

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.

Upvotes: 0

Views: 39

Answers (5)

Ulrich Tevi Horus
Ulrich Tevi Horus

Reputation: 23

<?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;
                }
            }    
        } 
    }

Upvotes: 0

SOFe
SOFe

Reputation: 8214

$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.

Upvotes: 0

Naumov
Naumov

Reputation: 1167

You can use array_map function

$my_array = [
['social_channel' => 'twitter', 'link' => '[email protected]'],
['social_channel' => 'mail', 'link' => '[email protected]'],
];

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

$result = array_map("getMailArray",$my_array);

Upvotes: 1

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

Try this:

$arr1 = array(array('social_channel' => 'twitter', 'link' =>    '[email protected]'),
             array('social_channel' =>  'mail', 'link' =>   '[email protected]'));
$emailArr = array();
foreach ($arr1 AS $arr) {
    $emailArr[] = $arr['link'];
}
print_r($emailArr);

Upvotes: 0

Grant J
Grant J

Reputation: 1065

Assuming you've got the following:

$my_array = [
    ['social_channel' => 'twitter', 'link' => '[email protected]'],
    ['social_channel' => 'mail', 'link' => '[email protected]'],
];

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.
}

Upvotes: 1

Related Questions