Skip to content
Advertisement

PHP remove multiple array key inside an array with multiple values

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement