我有一个像这样的数组结构
Array
(
[0] => stdClass Object
(
[foo] => 9992
[bar] => 1508
)
[1] => stdClass Object
(
[foo] => 10115
[bar] => 1598
)
[2] => stdClass Object
(
[foo] => 10263
[bar] => 1690
)
[3] => stdClass Object
(
[foo] => 10363
[bar] => 1794
)
[4] => stdClass Object
(
[foo] => 10486
[bar] => 1904
)
)
现在我想将此结构转换为:
Array
(
[0] => stdClass Object
(
[name] => 'foo'
[data] => Array (
9992, 10115, 10263, 10363, 10486
)
)
[1] => stdClass Object
(
[name] => 'bar'
[data] => Array(
1508, 1598, 1690, 1794, 1904
)
)
)
我已经尝试过这段代码,但它没有给我预期的结构
$return = array();
$i = 0;
foreach($object as &$row) {
foreach( $row as $key => $val ) {
$return[$i]['name'] = $key;
// This is my custom function that does the same
// thing for objects as array_search does for arrays
$search = object_search($key, $row);
if( $search ) {
$return[$search]['data'][] = $val;
} else {
$return[$i]['data'][] = $val;
}
}
$i++;
}
return $return;
答案 0 :(得分:2)
试试这个
$result = array();
foreach ($array1 as $row) {
foreach ($row as $key => $value) {
$result[$key][] = $value;
}
}
$result2 = array();
foreach ($result as $key => $value) {
$obj = array();
$obj['name'] = $key;
$obj['data'] = $value;
$result2[] = $obj;
}
代码可能会失败,但你明白了。
如果你能用php代码给我你的数组,我可以再次测试我的代码。
答案 1 :(得分:1)
$c1 = new stdClass();
$c1->foo = 123;
$c1->bar = 345;
$c2 = new stdClass();
$c2->foo = 444;
$c2->bar = 555;
$arr = array();
$arr[] = $c1;
$arr[] = $c2;
$tfoo = array();
$tbar = array();
foreach($arr as $a) {
$tfoo[] = $a->foo;
$tbar[] = $a->bar;
}
$foo = array_unique($tfoo);
$bar = array_unique($tbar);
$result = array();
$result[0] = new stdClass();
$result[0]->name = "foo";
$result[0]->data = $foo;
$result[1] = new stdClass();
$result[1]->name = "bar";
$result[1]->data = $bar;
print_r($result);