【问题标题】:PHP remove multiple array key inside an array with multiple valuesPHP删除具有多个值的数组中的多个数组键
【发布时间】:2021-08-06 07:19:21
【问题描述】:

我发现我无法确定所需的输出。

我的 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

【问题讨论】:

    标签: php arrays multidimensional-array foreach array-unset


    【解决方案1】:

    您应该能够遍历源数据的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 2020-02-18
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2019-03-18
      • 1970-01-01
      相关资源
      最近更新 更多