PHP多维数组操作 [英] PHP multi dimensional array manipulation

查看:35
本文介绍了PHP多维数组操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数组

Array
(
    [0] => Array
        (
            [sample_id] => 3
            [time] => 2010-05-30 21:11:47
        )

    [1] => Array
        (
            [sample_id] => 2
            [time] => 2010-05-30 21:11:47
        )

    [2] => Array
        (
            [sample_id] => 1
            [time] => 2010-05-30 21:11:47
        )
)

而且我想在一个数组中获取所有 sample_id.有人可以帮忙吗?

And I want to get all the sample_ids in one array. can someone please help ?

这可以在没有 for 循环的情况下完成吗(因为数组非常大).

Can this be done without for loops (because arrays are very large).

推荐答案

这是我遇到过很多次的问题.没有一种简单的方法可以在 PHP 中展平数组.您必须循环它们,将它们添加到另一个数组中.如果失败,请重新考虑如何处理数据以使用原始结构而不需要展平.

This is a problem I've had MANY times. There isn't an easy way to flatten arrays in PHP. You'll have to loop them adding them to another array. Failing that rethink how you're working with the data to use the original structure and not require the flatten.

我想我会添加一些度量信息,我创建了一个数组 $data = array(array('key' => value, 'value' => other_value), ...); 我的数组中有 150,000 个元素.我比跑了 3 种典型的扁平化方法

I thought I'd add a bit of metric information, I created an array $data = array(array('key' => value, 'value' => other_value), ...); where there were 150,000 elements in my array. I than ran the 3 typical ways of flattening

$start = microtime();
$values = array_map(function($ele){return $ele['key'];}, $data);
$end = microtime();

产生的运行时间为:Run Time:0.304405 运行 5 次平均时间略低于 0.30

Produced a run time of: Run Time: 0.304405 Running 5 times averaged the time to just below 0.30

$start = microtime();
$values = array();
foreach ($data as $value) {
    $values[] = $value['key'];
}
$end = microtime();

产生了Run Time: 0.167301的运行时间,平均为0.165

Produced a run time of Run Time: 0.167301 with an average of 0.165

$start = microtime();
$values = array();
for ($i = 0; $i < count($data); $i++) {
    $values[] = $data[$i]['key'];
}
$end = microtime();

产生了 Run Time: 0.353524 的运行时间,平均为 0.355

Produced a run time of Run Time: 0.353524 with an average of 0.355

在每种情况下,对数据数组使用 foreach 都明显更快.这可能与 hte array_map() 实现的数组中每个元素执行函数的开销有关.

In every case using a foreach on the data array was significantly faster. This is likely related to the overhead of the execution of a function for each element in the array for hte array_map() implementation.

进一步我使用预定义的函数运行此测试.以下是On the Fly"(定义内联)和Pre Defined"(字符串查找)的 10 次迭代的平均数.

Further I ran this testing with a predefined function. Below are the average numbers over 10 iterations for 'On the Fly' (defined inline) and 'Pre Defined' (string lookup).

Averages:
  On the fly: 0.29714539051056
  Pre Defined: 0.31916437149048

这篇关于PHP多维数组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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