【问题标题】:Cannot Assign Key => Value to Foreach Array无法将键 => 值分配给 Foreach 数组
【发布时间】:2019-05-28 02:24:06
【问题描述】:

我有以下国家/地区数组($countryIso = array("US","BR","CL");),我的想法是创建一个新数组来显示以下架构:

('美国', 200)

我尝试创建以下结构:

    $countryIso = array("US","BR","CL");

    foreach ($countryIso as $isocode) {
        $productcalc[] = "'" . strtoupper($isocode) . "'" . ',' . number_format($this->product->calculate($product = $product, $countryIso = $isocode), 0, '.', ',');
    }

尽管我可以创建一个外观相似的格式,但我意识到该数组的格式不正确。当我检查输出显示以下内容:

数组 ( [0] => 'US',200

key 是 [0] 而不是 US。

关于如何使用

创建键 => 值结果的任何想法

数组([美国] => 200

在我的代码中使用 foreach 结构?我尝试使用 array_combine 之类的变体将 countryIso 数组与 productcalc 数组结合,但没有成功

【问题讨论】:

  • $array['US'] = 200;
  • $array[$isocode] = 200;
  • array([$isocode],[$productcalc]) 显示 [1] => 数组 ( [0] => 数组 ( [0] => 'US',900 [1] => 'BR',1,215 [2] => 'CL',1,446 ) ) 但数组仍然 [0]
  • 如果您要向问题添加信息。 请将其编辑到您的问题中
  • 不确定这段代码应该做什么calculate($product = $product, $countryIso = $isocode)

标签: php arrays laravel-5


【解决方案1】:

只需使用正确的值定义数组即可。

$countryIso =[
    "US" => 200,
    "BR" => 300,
    "CL" => 400,
];

如果需要计算值,请使用:

$countryIso = array("US","BR","CL");

foreach ($countryIso as $isocode) {
    $productcalc[strtoupper($isocode)] = number_format($this->product->calculate($product = $product, $countryIso = $isocode), 0, '.', ',');
}

现在 $productcalc 是您需要的数组。

【讨论】:

  • 我明白,但我的问题是我无法根据 $productcalc 结果分配密钥。比如 $countryIso US 和 productcalc = 200。
【解决方案2】:

您可以保留您的 iso 数组,只需 combine 数组:

<?php
    $iso = ['US', 'BR', 'CL'];
    $values = [200, 300, 400]; # obviously populate this with your actual values

    $newArray = array_combine($iso, $values); # array_combine($keys, $values)
    echo '<pre>'. print_r($newArray, 1) .'</pre>';

编辑:如果通过 iso 值获得值,则进一步思考

<?php
    $iso = ['US', 'BR', 'CL'];
    $newArray = [];

    foreach ($iso as $val)
    {
        $newArray[$val] = getValueFromIso($val); # not a real function - just an example
    }

【讨论】:

  • 第一个工作完美,但在我的情况下,foreach 将 countryIso 作为计算值,我无法将 key =>value 像 $countryIso 作为 key =>value
  • @s_h 不确定我是否遵循您评论的第二部分抱歉哈哈,但如果第一个有效并且您可以创建两个这样的数组,那么我很乐意提供帮助 :)
  • 谢谢,我错过了以下概念 $newArray[$val]。新年快乐!。
猜你喜欢
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多