Array (
[0] => Array (
[Name] => Banana
[Percentage] => 25
[Sum] => 70
)
[1] => Array (
[Name] => Banana
[Percentage] => 25
[Sum] => 168
)
[2] => Array (
[Name] => Apple
[Percentage] => 14
[Sum] => 8
)
)
如果键[Name]
和[Percentage]
与数组中的另一个键相似,如何合并值?
例如,我搜索的内容如下:
Array (
[0] => Array (
[Name] => Banana
[Percentage] => 25
[Sum] => 238
)
[1] => Array (
[Name] => Apple
[Percentage] => 14
[Sum] => 8
)
)
这是我尝试的内容:
foreach($myArray as $value){
$Name = $value['Name'];
if(isset($result[$Name]))
$index = count($result[$Name]);
else
$index = 1;
$result['Name'] = $Name;
$result['Percentage'] = $value['Percentage'];
$result['Sum'] += $value['Sum'];
}
$result = array_values($result);
感谢。
答案 0 :(得分:1)
你现在拥有的问题是你只是复制原始数组中已有的内容,除非你使用 val arrayOfArrayOfAnys=Array(
Array("aString",0L ,3.14159),
Array("bString",9876543210L,2.71828)
)
val rddOfRows=spark.sparkContext.parallelize(arrayOfArrayOfAnys).map(f=>Row.fromSeq(f.toSeq))
/* If one knows the datatypes, for instance from JDBC queries as to RDBC column metadata:
* Consider constructing the schema from an Array[StructField]. This would allow looping over
* the columns, with a match statement applying the appropriate sql datatypes as the second
* StructField arguments.
*/
val sf=new Array[StructField](3)
sf(0)=StructField("colOfStrings",StringType)
sf(1)=StructField("colOfLongs" ,LongType )
sf(2)=StructField("colOfDoubles",DoubleType)
val df=spark.sqlContext.createDataFrame(rddOfRows,StructType(sf.toList))
df.show
投入失败的总和。请参阅以下带有符号的新示例:
$result['Sum'] += $value['Sum'];
答案 1 :(得分:0)
基本上你想要做的是遍历数组并将当前项目与前一项目进行比较,随时构建一个独特项目数组。
如果Name
和Percentage
在当前项和上一项之间相等,则只需将当前项的总和添加到上一项。如果没有,那么只需将当前项添加到新数组。
这对你有用:
$newArray = Array();
foreach ($myArray as $currentItem) {
if (isset($prevItem) && $currentItem['Name'] == $prevItem['Name'] && $currentItem['Percentage'] == $prevItem['Percentage']) {
// append sum to previous item
$prevItem['Sum'] += $currentItem['Sum'];
} else {
// add current item to array
$newArray[] = $currentItem;
$lastIndex = count($newArray) - 1;
$prevItem = &$newArray[$lastIndex];
}
}
注意:这假定数组已按名称和百分比排序。