我有一个多维数组,如下所示:
$arrayOne = array(
0 => array(
"no"=> "1",
"value"=>100
),
1=> array(
"no"=> "2",
"value"=>"20"
)
2=> array(
"no"=> "3",
"value"=>"30"
)
);
我想创建一个新的数组,其中:
1st new array value = 100+50 (equal to 150, where 50 is an amount that I want to add to the array).
2nd new array value = 20+150 (equal to 170, where 150 is the total of 1st new array)
3rd new array value = 30+170 (equal to 200, where 170 is the total of 2nd new array)
这可行吗?输出应为:
$newArrayOne = array(
0 => array(
"no"=> "1",
"value"=>150
),
1=> array(
"no"=> "2",
"value"=>"170"
)
2=> array(
"no"=> "3",
"value"=>"200"
)
);
这个要求对我来说有点太复杂了。谁能分享我这个概念,我会尽力弄清楚。
非常感谢。
答案 0 :(得分:0)
类似的东西:
$arrayOne[0]['value'] += 50;
for($i=1; $i<count($arrayOne); $i++) {
$arrayOne[$i]['value'] += $arrayOne[$i-1]['value'];
}
答案 1 :(得分:0)
您可以使用经典 foreach
循环
$arrayOne = //Your array here...
$newArrayOne = array();
$toAdd = 50;
foreach( $arrayOne as $key => $val ) {
$newArrayOne[$key] = $val; //Assign the value to $newArrayOne
if ( $key === 0 ) $newArrayOne[$key]['value'] += $toAdd; //Modify the value: If $key is 0, add 50
else $newArrayOne[$key]['value'] += $newArrayOne[ $key - 1 ]['value']; //If $key is not 0, add the value of last entry of $newArrayOne
}
这将导致:
Array
(
[0] => Array
(
[no] => 1
[value] => 150
)
[1] => Array
(
[no] => 2
[value] => 170
)
[2] => Array
(
[no] => 3
[value] => 200
)
)
答案 2 :(得分:0)
$first_array = array(
0 => array(
"no"=> "1",
"value"=>100
),
1=> array(
"no"=> "2",
"value"=>"20"
),
2=> array(
"no"=> "3",
"value"=>"30"
)
);
$to_be_added = 50; //this is what you want to add to your first value
foreach ($first_array as $key => $val){
$to_be_added = (int)$val['value'] + $to_be_added ; //type casting
$newArrayOne[$key]['no']= $val['no'];
$newArrayOne[$key]['value']= $to_be_added;
}
print_r($newArrayOne);
请注意im类型将您的值强制转换为整数,因为并非您的所有“值”都是整数。
您的输出
Array ( [0] => Array ( [no] => 1 [value] => 150 ) [1] => Array ( [no] => 2 [value] => 170 ) [2] => Array ( [no] => 3 [value] => 200 ) )
答案 3 :(得分:0)
$ newArray = $ arrayOne;
foreach($ arrayOne as $ k => $ v){
$newArray[$k]['value'] = ($k == 0) ? array_sum(array_column($arrayOne, 'value')) : $newArray[$k-1]['value'] + $arrayOne[$k]['value'];
}
print_r($ newArray);
答案 4 :(得分:0)
我为您付出了很多努力。我希望这对您有用。
<?php
echo "<pre>";
$arrayOne = array(
0 => array(
"no"=> "1",
"value"=>100
),
1=> array(
"no"=> "2",
"value"=>"20"
),
2=> array(
"no"=> "3",
"value"=>"30"
)
);
$valnewarr = array();
$valdata = 50;
$i = 0;
foreach($arrayOne as $val){
$valdata = $val['value']+$valdata;
$valnewarr['no'] = ++$i;
$valnewarr['value'] = $valdata;
$newArrayOne[] = $valnewarr;
}
print_r($newArrayOne);
?>