【问题标题】:Loop into an array if I have a key in PHP如果我在 PHP 中有一个键,则循环进入一个数组
【发布时间】:2018-06-22 12:13:55
【问题描述】:

如何循环到这个数组的plans 数据:

$currencies = array(
    array(
        'currency' => 'mxn', 
        'sign'     => '$',
        'plans'    => array(
            'tiny'   => 429,
            'small'  => 1319,
            'medium' => 3399,
            'big'    => 6669
        )
    ),
    array(
        'currency' => 'usd', 
        'sign'     => '$',
        'plans'    => array(
            'tiny'   => 29,
            'small'  => 319,
            'medium' => 399,
            'big'    => 669
        )
    )
);

如果我只有currency

$currency = 'mxn';

我试过了:

foreach($currencies as $currency => $info) {
    if($info['currency'] = 'mxn') {
        ....
    }
}

谢谢。

【问题讨论】:

标签: php arrays


【解决方案1】:

这个问题是展示更好方法的绝佳机会。

代码:(演示:https://3v4l.org/dU09B

$currencies = [
    'mxn' => [
        'sign'  => '$',
        'plans' => [
            'tiny'   =>  429,
            'small'  => 1319,
            'medium' => 3399,
            'big'    => 6669
        ]
    ],
    'usd' => [
        'sign'  => '$',
        'plans' => [
            'tiny'   =>  29,
            'small'  => 319,
            'medium' => 399,
            'big'    => 669
        ]
    ]
];

$currency='mxn';

if(!isset($currencies[$currency])){
    echo "$currency was not found in the currencies array.";
}else{
    echo "In $currency:\n";
    foreach($currencies[$currency]['plans'] as $size=>$price){
        echo "\t$size costs {$currencies[$currency]['sign']}$price\n";
    }
}

输出:

In mxn:
    tiny costs $429
    small costs $1319
    medium costs $3399
    big costs $6669

解释:

由于货币名称在逻辑上是唯一的,因此您可以通过将货币名称声明为子数组键来减小查找数组的整体大小。

如果您要将同样的数据存储在数据库中,您可以将货币名称指定为主键。

为了提高效率和直接编码,新的数组结构将允许您使用isset() 快​​速确定您想要的货币是否存在于多维数组中。

你的问题标题问:如果我在 PHP 中有一个键,则循环进入一个数组 我认为这意味着 needle 可能不在干草堆。也许这不是您的意思,但这种考虑对于构建到您的代码中很重要。

在尝试使用密钥之前验证密钥是否存在于多维数组中是必不可少的(以避免通知 ftom php)。


如果您无法或对修改数据结构不感兴趣,请确保您采用两种最佳做法:

  1. break您的搜索foreach在找到您的货币后循环;或致电array_search(),它会为您执行此操作。在收到所需数据后迭代数组中的剩余项目是浪费/低效的。

  2. 编写一个条件来处理找不到货币的可能性。因为尝试访问:$currencies[false] 并不适合您。

【讨论】:

    【解决方案2】:

    如果我理解正确,您想在“货币”等于“mxn”时循环数组“计划”。这里是:

    <?php
    foreach($currencies as $key => $data) {
      if($data['currency'] == 'mxn')
      {
        echo 'List of plans: <br />';
        foreach($data['plans'] as $item){
            echo $item.'<br />';
        }
      }
    }
    ?>
    

    首先,代码检查哪个数组是 mxn 货币并在“plans”数组上循环。

    只是用简化的替代方法来补充帖子:

    <?php
    $key = array_search('mxn', array_column($currencies, 'currency'));
    foreach($currencies[$key]['plans'] as $item){
        echo $item.'<br />';
    }
    ?>
    

    【讨论】:

    • 这不是一个精确的答案,因为它会在找到目标子数组后继续迭代。有一个 php 函数的组合提供了一种优越的方法。
    • 我知道。我总是尝试用更多的代码向人们解释到底发生了什么,但我发布了一个简化或“高级”的方法。感谢您的关注@mickmackusa
    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2019-04-29
    • 2010-12-05
    相关资源
    最近更新 更多