我有一个正在循环遍历数组的foreach,然后我从foreach中提取出该数组的信息。我需要将这些信息放入一个单独的空数组中。我有工作,有点儿。这是我的代码:
newArray = array();
foreach ($result as $value) {
newArray[] = $value['sample1'];
newArray[] = $value['sample2'];
newArray[] = $value['sample3'];
}
print_r(newArray);
这将打印一个类似于:
的关联数组{
0: "1",
1: "1",
2: "blah",
3: "etc through as many values as I have",
}
相反,我需要让它形成一个看起来像这样的数组:
{
0: {
0: "1",
1: "1",
2: "blah"
},
1: {
0: "etc"
}
}
关于如何创建新的多维数组的任何建议?
答案 0 :(得分:2)
构建一个包含所需原始部分的临时数组,然后将该临时数组添加到newArray中,如下所示
foreach ($result as $value) {
$t = [ $value['sample1'], $value['sample2'], $value['sample3'] ];
$newArray[] = $t;
}
或者您使用的是旧的PHP
foreach ($result as $value) {
$t = array( $value['sample1'], $value['sample2'], $value['sample3'] );
$newArray[] = $t;
}
或简写
foreach ($result as $value) {
$newArray[] = [ $value['sample1'], $value['sample2'], $value['sample3'] ];
}
和旧的PHP
foreach ($result as $value) {
$newArray[] = array( $value['sample1'], $value['sample2'], $value['sample3'] );
}
答案 1 :(得分:0)
使用$newArray[]
时,每次都会在数组中创建一个新项目。
你可以试试这个:
foreach ($result as $key => $value) {
$newArray[$key][] = $value['sample1'];
$newArray[$key][] = $value['sample2'];
$newArray[$key][] = $value['sample3'];
}
print_r($newArray);
答案 2 :(得分:0)
foreach ($result as $value) {
$newArray[] = [
$value['sample1'],
$value['sample2'],
$value['sample3']
];
}