微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP删除具有多个值的数组内的多个数组键

如何解决PHP删除具有多个值的数组内的多个数组键

我发现我无法弄清楚所需的输出

我有 JSON 原始数据包含这个:

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
                            
                        )

                )   

    )   
)

这是我试过的

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

                }
        }
    }

我想获取数组的所有键,如果代码有多个值,则不要回显它。

所需输出示例:

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

解决方法

您应该能够循环遍历源数据的 data 键,提取标题和代码并在代码为 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";
}

输出(用于您的示例数据):

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

Demo on 3v4l.org

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。