1

当前阵列:

stdClass Object (
[name1] => Someting very useful
[text1] => Description of something useful
[url1] => link.to/useful
[name2] => Someting very useful2
[text2] => Description of something useful2
[url2] => link.to/useful2
[name3] => Someting very useful3
[text3] => Description of something useful3
[url3] => link.to/useful3
) 

我需要: 创建多维数组,其中 name1、text1、url1 等键将被放入自己的数组中。如何做到这一点?

4

4 回答 4

2

我想你想要:

$array = array_chunk((array)$object, $chunkSize = 3, $preserveKeys = true);

$object上面是你的对象)

这会将您的对象转换为一个数组,并将其拆分为较小的数组,每个数组包含 3 个元素

于 2013-02-18T14:05:41.483 回答
1

好;

$array = (array) $object;
于 2013-02-18T14:01:35.930 回答
1

即使您没有一致的输入,这也将非常通用,例如每个孩子恰好三个属性。此外,对象中的属性不必按任何特定顺序排列。

//$obj is the object you have in the question
$objects = array();
foreach($obj as $key => $val) {
    $result = preg_match('%([a-zA-Z]+)([0-9]+)%', $key,$matches);
    $new_key = $matches[2];
    $property = $matches[1];
    if(!isset($objects[$new_key])) {
        $objects[$new_key] = array();
    }
    $objects[$new_key][$property] = $val;
}
于 2013-02-18T14:10:25.260 回答
1
$array = array();
$c = count($object) / 3;
(Array) $object;

for($i = 1; $i <= $c; $i++){

    $array[$i]['name' + $i] = $object['name' + $i];
    $array[$i]['text' + $i] = $object['text' + $i];
    $array[$i]['url' + $i] = $object['url' + $i];

}
于 2013-02-18T14:11:02.467 回答