ruraldev
ruraldev

Reputation: 187

Extract values from multidimensional array using key value

I wonder if someone can help me extract values from an array by key value rather than array number.

$json = json_decode($stock, true);
print_r($json);
$sims = $json['stock'][1]['sims'];

foreach ($sims as $sim)
{
    echo nl2br($sim . "\n");
}

The output from print_r($json) is:

Array ( [stock] => Array (
[0] => Array
( [operator] => ECL [sims] => Array
( [0] => 8944122616994 [1] => 89650264517182 [2] => 894412265075 [3] => 894412 ) )
[1] => Array
( [operator] => JT [sims] => Array
( [0] => 89445023065 [1] => 894156673081 [2] => 8944501 [3] => 89445027 ) ) ) )

It appears that sometimes the data I want is not in array number 1 hence I would like to extract it based on "[operator] => JT" I've been trying various ideas but it never seems to work.

Upvotes: 1

Views: 2712

Answers (3)

Nabin Kunwar
Nabin Kunwar

Reputation: 1996

You can accomplice it by using array_search and array_column

This will give you the multidimensional array key

$key = array_search("JT", array_column($json['stock'], 'operator'));

Then you can do

$sims = $json['stock'][$key]['sims'];
print_r($sims) //this will print desired array

Upvotes: 4

Tobias Xy
Tobias Xy

Reputation: 2069

Write a function like this:

function getSims(array $array) {
    $sims = [];

    foreach ($array as $data) {
        if ($data['operator'] == 'JT') {
            return $data['sims'];
        }
    }
    // here you could also throw an exception or return something else
    return [];
}

and use it like this:

$json = json_decode($stock, true);
$sims = getSims($json['stock']);

Upvotes: 0

Ben
Ben

Reputation: 9001

Try:

$json = json_decode($stock, true);

foreach($json["stock"] as $arr){
    echo $arr["operator"]."\n";
    foreach($arr["sims"] as $sim){
        echo $sim."\n";
    }
    echo "\n";
}

This would output (for example):

ECL
8944122616994
89650264517182
894412265075
894412

JT
89445023065
894156673081
8944501
89445027

Upvotes: 0

Related Questions