0

I find I can't figure out the desired output.

I have JSON raw data contains this:

Array
(
    [data] => Array
        (
        
            [0] => Array
                (
                    [title] => currency1
                    [tickers] => Array
                        (
                            [0] => USD
                        )

                )
            
            [1] => Array
                (
                    [title] => currency2
                    [tickers] => Array
                        (
                            [0] => USD
                            [1] => EUR
                        )

                )
                
            [2] => Array
                (
                    [title] => currency3
                    [tickers] => Array
                        (
                            [0] => USD
                            
                        )

                )   

    )   
)

This is what I have tried

$num =0;
foreach ($json_data as $key => $story){
    
    $num++;
    foreach($story as $subkey => $subvalue){
        if(is_array($subvalue)){
            
                $title = $story[$subkey]['title']; 
                $tickers = $story[$subkey]['tickers'][$num]; 
                
                
                foreach($tickers as $key2 => $val2){
                    
                    if($val2>=1){
                           unset($story);      
                         
                    }else{
                        
                        //echo output
                    }

                }
        }
    }

I want to get all the keys of the arrays and if tickers has multiple value don't echo it.

Sample desired output:

curreny1 Key is 0 and tickers is USD
curreny3 Key is 2 and tickers is USD
0

1 Answer 1

1

You should be able to just loop over the data key of your source data, extracting the title and tickers and outputting a result if the count of the tickers is 1:

foreach ($json_data['data'] as $key => $story) {
    $tickers = $story['tickers'];
    if (count($tickers) != 1) continue;
    $title = $story['title'];
    echo "$title Key is $key and tickers is {$tickers[0]}\n";
}

Output (for your sample data):

currency1 Key is 0 and tickers is USD
currency3 Key is 2 and tickers is USD

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

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.