PHP添加元素的多维度阵列的每个子阵列 [英] PHP Add element to every sub array of multi dimension array

查看:180
本文介绍了PHP添加元素的多维度阵列的每个子阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,看起来类似的东西。

I have an array that looks something like that

array(
     [0] => array(
               'id' => 1,
               'title' => 'title 1',
     ),
     [1] => array(
               'id' => 10,
               'title' => 'title 10',
     ),
     [2] => array(
               'id' => 11,
               'title' => 'title 11',
     ),
     [...]
);

我要的元素添加到所有的子阵列。这是我加入相同的元素。因此,新的阵列看起来像:

I want to add an element to all the sub array. It's the same element i'm adding. so the new array will look like :

array(
     [0] => array(
               'id' => 1,
               'title' => 'title 1',
               'type'  => 'bag',
     ),
     [1] => array(
               'id' => 10,
               'title' => 'title 10',
               'type'  => 'bag',
     ),
     [2] => array(
               'id' => 11,
               'title' => 'title 11',
               'type'  => 'bag',
     ),
     [...]
);

有没有办法做到这一点的不反复的第一阵列上
这会是一个很大的数组。我在寻找这样做的最快方式。

Is there a way to do it without iterating on the the first array? It's gonna be a big array. I'm looking for the fastest way to do it.

推荐答案

无论速度人们可能希望通过使用array_walk获得,是失去功能的开销。既然你在你的评论指出,该阵列是一个数据库查询的结果,您可以直接在您的结果值加上设置 SELECT'袋'AS类型 以您的SQL语句。

Whatever speed one might hope to gain by using array_walk, is lost with function overhead. Since you stated in your comments that the array is a result of a db query, you can simply include the bag value in your result set by adding SELECT 'bag' AS 'type' to your SQL statement.

$start = 0; $end = 0;

$orig = array(
    array('id' => 1,  'title' => 'title 1'),
    array('id' => 10, 'title' => 'title 10'),
    array('id' => 11, 'title' => 'title 11')
);

// A
$start = microtime(true);
for ($a=0; $a<1000; $a++) {
    $els1 = $orig;
    array_walk($els1, function(&$val, $key){$val['type'] = 'bag';});
}
$end = microtime(true);
echo 'A: ', $end - $start,  "<br />\n";

// B
$start = microtime(true);
for ($b=0; $b<1000; $b++) {
    $els2 = $orig;
    foreach ($els2 as &$el) {
        $el['type'] = 'bag';
    }
    unset($el);
}
$end = microtime(true);
echo 'B: ', $end - $start,  "<br />\n";

/* output:

A: 0.0076138973236084
B: 0.0047528743743896

A: 0.0075309276580811
B: 0.0045361518859863

A: 0.0075531005859375
B: 0.062379837036133

A: 0.0075340270996094
B: 0.0044951438903809

A: 0.0074868202209473
B: 0.0044751167297363

A: 0.0076088905334473
B: 0.0048189163208008

*/

这篇关于PHP添加元素的多维度阵列的每个子阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆