0

如何在特定键下将元素添加到我的数组中?

这是我使用 foreach 之前的数组输出。如您所见,错误字段为空。我想填写。

Array (
  [0] => Array (
    [transactionid] => 2223
    [created] => 26-02-13 14:07:00
    [cardid] => 10102609
    [pricebefordiscount] => 68900
    [error] =>
  )

这是我的前锋。如您所见,我已经尝试通过实施来完成这项工作$arrayname['index'] = $value;。但这不起作用,当我吐出print_r. 为什么会这样?

foreach ($samlet as $key)
{
    if ($key['pricebefordiscount'] > '200000') 
    {
        $samlet['error'] = "O/2000";
    }
    if ($key['cardid'] === '88888888') 
    {
        $samlet['error'] = "Testscan";
    }
}

这是所需的输出:

Array (
  [0] => Array (
    [transactionid] => 2223
    [created] => 26-02-13 14:07:00
    [cardid] => 10102609
    [pricebefordiscount] => 68900
    [error] => "Testscan"
  )
4

4 回答 4

3

更改您的foreach, 以便您拥有“主” $samlet数组中使用的索引:

foreach($samlet as $key => $array)
{
    if ($array['cardid'] === '88888888')
    {
        $samlet[$key]['error'] = '0/2000';
    }
}

等等...

于 2013-02-27T09:55:29.087 回答
1

试试这个 :

foreach ($samlet as &$key){

    if ($key['pricebefordiscount'] > '200000'){
         $key['error'] = "O/2000";
    }
    if ($key['cardid'] === '88888888'){
        $key['error'] = "Testscan";
    }

}
于 2013-02-27T09:55:50.263 回答
1

根据PHP 手册

为了能够直接修改循环内的数组元素,在 $value 之前加上 &。在这种情况下,该值将通过引用分配。

所以你的代码应该是这样的:

<?php
foreach ($samlet as &$key)
{

    if ($key['pricebefordiscount'] > '200000') 
    {
         $key['error'] = "O/2000";
    }
    if ($key['cardid'] === '88888888') 
    {
        $key['error'] = "Testscan";
    }
}
于 2013-02-27T09:56:09.430 回答
0

试试这个

foreach ($samlet as $key=>$value)
{

    if ($value['pricebefordiscount'] > '200000') 
    {
         $samlet[$key]['error'] = "O/2000";
    }
        if ($value['cardid'] === '88888888') 
    {
        $samlet[$key]['error'] = "Testscan";
    }
}
于 2013-02-27T09:55:02.070 回答