PHP-将数组转换为新数组



当前阵列:

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(等等)这样的键将被放入自己的数组中。如何做到这一点?

我想你想要:

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

$object是您上面的对象)

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

井;

$array = (array) $object;
$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];
}

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

//$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;
}

相关内容

  • 没有找到相关文章

最新更新