我有一组由于mysql表的查询而生成的数组,在“while”循环中生成:
while ($row = mysql_fetch_array($result)) {
$k_id = $row['kw'];
$path[$level] = $k_id;
if(array_search('7', $path)) {
$it = new CachingIterator(new ArrayIterator($path));
$t1 = array();
foreach ( $it as $v ) {
$var = array("no" => $v,"to" => 0);
if ($it->hasNext()) {
$var["to"] = $it->getInnerIterator()->current();
}
$t1[] = $var;
}
extract($t1, EXTR_PREFIX_ALL, "t1");
for ($i = 0; $i < sizeof($t1); $i++) {
$dmp = print_r($t1[$i], result);
echo $dmp."<br />";
}
}
}
echo $ dmp的结果是一组数组:
Array ( [no] => 2 [to] => 1 )
Array ( [no] => 1 [to] => 4 )
Array ( [no] => 4 [to] => 7 )
Array ( [no] => 7 [to] => 0 )
Array ( [no] => 2 [to] => 1 )
Array ( [no] => 1 [to] => 5 )
Array ( [no] => 5 [to] => 7 )
Array ( [no] => 7 [to] => 0 )
Array ( [no] => 2 [to] => 1 )
Array ( [no] => 1 [to] => 6 )
Array ( [no] => 6 [to] => 7 )
Array ( [no] => 7 [to] => 0 )
Array ( [no] => 2 [to] => 1 )
Array ( [no] => 1 [to] => 3 )
Array ( [no] => 3 [to] => 7 )
Array ( [no] => 7 [to] => 0 )
我的问题是如何使用相同的“no”键值合并数组
mysql_fetch之前的var_dump:
array(0) { } array(1) { [0]=> string(1) "2" } array(2) { [0]=> string(1) "2" [1]=> string(1) "1" } array(3) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(1) "4" }
因此,我想获得数组,我可以轻松地从以下代码生成这样的代码:
"nodeTo": "4",
"nodeFrom": "1"
"nodeTo": "5",
"nodeFrom": "1"
"nodeTo": "6",
"nodeFrom": "1"
"nodeTo": "3",
"nodeFrom": "1"
"id": "1"
答案 0 :(得分:0)
您可以替换
$t1[] = $var;
用
$t1[$v][] = $var;
它将根据ID进行分组...有关如何输出结果的示例:
foreach ( $t1 as $no => $group ) {
echo "Merge $no <br />" ;
foreach ( $group as $list ) {
var_dump($list);
}
}
答案 1 :(得分:0)
我真的建议你在从sql中获取结果时直接创建正确的数组结构。这将为您节省额外的foreach循环。
为了完整,我为你准备了一个例子,你怎么能像你想象的那样做:(为了好玩;))
$a = array (
array ('no' => 2, 'to' => 1), // |___ will be merged
array ('no' => 2, 'to' => 1), // |
array ('no' => 2, 'to' => 2),
array ('no' => 3, 'to' => 2)
);
$result = array();
foreach($a as $item) {
if(!array_key_exists($item['no'], $result)) {
$result[$item['no']] = array($item['to']);
} else if(!in_array($item['to'], $result[$item['no']], TRUE)) {
$result[$item['no']][] = $item['to'];
}
}
// get all to values with no=2 :
$elements = $result[2];
转换后的结果数组的var_dump可能有助于理解发生了什么:
//
var_dump($result);
/* Output:
array(2) {
[2] => <---- 'no' value as index
array(2) {
[0] => -
int(1) |__ different 'to' values
[1] => |
int(2) -
}
[3] => <---- 'no' value as index
array(1) {
[0] =>
int(2) <------ 'to' value for 'no'==3
}
}
*/
正如我所说,你应该在从sql中获取结果时直接创建这个数组结构。不幸的是,如果没有$path
的内容,我就无法说明如何实现这一目标。
答案 2 :(得分:0)
foreach ($t1 as $dmp) {
$combined[$dmp["no"]][] = $dmp["to"];
}
结果:
Array
(
[2] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 3
)
[4] => Array
(
[0] => 7
)
[7] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
[5] => Array
(
[0] => 7
)
[6] => Array
(
[0] => 7
)
[3] => Array
(
[0] => 7
)
)