CURRENT ARRAY:
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(等等)的键将被放入自己的数组中。怎么做到这一点?
答案 0 :(得分:2)
我想你想要:
$array = array_chunk((array)$object, $chunkSize = 3, $preserveKeys = true);
($object
是您上面的对象)
这会将您的对象转换为数组,并将其拆分为每个包含3个元素的较小数组
答案 1 :(得分:1)
好;
$array = (array) $object;
答案 2 :(得分: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;
}
答案 3 :(得分: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];
}