1

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.

3
  • This is a bit unclear - what is the output you're trying to get? Commented Feb 12, 2016 at 15:49
  • Could you maybe give us your JSON string and a clear example of what you're trying to extract from it? Commented Feb 12, 2016 at 15:51
  • Whoever downvoted its a very good question. Please add your comment Commented Feb 12, 2016 at 17:10

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.