我有一个来自excel文件的数组。
$array = [
['parent 1', '10000', '20000'],
['parent 1', '15000', '21000'],
['parent 2', '13000', '22000'],
['parent 2', '11000', '5000'],
];
如何使用php将上面的数组转换为下面的数组
$array = [
'parent 1' => [
['10000', '20000'],
['15000', '21000']
],
'parent 2' => [
['13000', '22000'],
['11000', '5000']
]
];
答案 0 :(得分:3)
您需要遍历数组以将第一个值作为键并保留其值。
版本1
$result = [];
foreach ($arr as $k => $v) {
$result[$v[0]][] = [ // making first value as key and reset its values
$v[1], $v[2],
];
}
print_r($result);
Demo。
编辑
版本2
$result = [];
foreach ($arr as $k => $v) {
$result[array_shift($v)][] = $v;
}
print_r($result);
输出
Array
(
[parent 1] => Array
(
[0] => Array
(
[0] => 10000
[1] => 20000
)
[1] => Array
(
[0] => 15000
[1] => 21000
)
)
[parent 2] => Array
(
[0] => Array
(
[0] => 13000
[1] => 22000
)
[1] => Array
(
[0] => 11000
[1] => 5000
)
)
)
答案 1 :(得分:0)
尝试这个简单而精确的解决方案。
$array = [
['parent 1', '10000', '20000'],
['parent 1', '15000', '21000'],
['parent 2', '13000', '22000'],
['parent 2', '11000', '5000'],
];
$output = [];
foreach ($array as $key => $value) {
$output[$value[0]][] = array($value[1],$value[2]);
}
print_r($output);
parent 1
和parent 2
位于0
索引上,其他实体位于1
和2
索引上。我在每次迭代时都将1
和2
的索引值分配给新数组中的0
索引
输出
Array
(
[parent 1] => Array
(
[0] => Array
(
[0] => 10000
[1] => 20000
)
[1] => Array
(
[0] => 15000
[1] => 21000
)
)
[parent 2] => Array
(
[0] => Array
(
[0] => 13000
[1] => 22000
)
[1] => Array
(
[0] => 11000
[1] => 5000
)
)
)
这里是demo
答案 2 :(得分:0)
这是一个解决方案:
import { StyleSheet, View, Alert, Platform, Button } from 'react-native';
export default class MyProject extends Component {
constructor(props) {
super(props)
Obj = new Second();
}
CallFunction_1=()=>{
Obj.SecondClassFunction() ;
}
CallFunction_2=()=>{
Obj.SecondClassFunctionWithArgument("Hello Text");
}
render() {
return (
<View style={styles.MainContainer}>
<View style={{margin: 10}}>
<Button title="Call Another Class Function Without Argument" onPress={this.CallFunction_1} />
</View>
<View style={{margin: 10}}>
<Button title="Call Another Class Function With Argument" onPress={this.CallFunction_2} />
</View>
</View>
);
}
}
class Second extends Component {
SecondClassFunction=()=>{
Alert.alert("Second Class Function Without Argument Called");
}
SecondClassFunctionWithArgument=(Value)=>{
Alert.alert(Value);
}
}
const styles = StyleSheet.create(
{
MainContainer: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
backgroundColor: '#F5FCFF',
paddingTop: (Platform.OS) === 'ios' ? 20 : 0
}
});
输出:
$array = [
['parent 1', '10000', '20000'],
['parent 1', '15000', '21000'],
['parent 2', '13000', '22000'],
['parent 2', '11000', '5000'],
];
$new_array = array();
foreach($array as $a) {
$temp = array_slice($a, 1);
if(!array_key_exists($a[0], $new_array)) {
$new_array[$a[0]] = array();
}
array_push($new_array[$a[0]], $temp);
}
print_r($new_array)