php array_column与不连续的索引返回错误的索引 [英] php array_column with unsequential index returns wrong index

查看:88
本文介绍了php array_column与不连续的索引返回错误的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在php中有一个这样的数组:

So I have an array in php like this:

array(
  22 => array()
  23 => array()
  25 => array()
)

我正在search_array中使用array_column在子数组中搜索列。

I am using array_column in search_array to search a column in the sub arrays.

$index=array_search('needlehere',array_column(myarray,'columnbeingsearchedhere'))

但是array_column没有使用正确的索引,但将它们重新索引为0,1,2 ...

But the array_column is not using the correct indexes, but reindexing them to be 0,1,2...

是否仍然要保留正确的索引?

Is there anyway to keep the correct indexes?

推荐答案

array_column()不维护索引(尽管它允许您从行中的其他数据列设置自己的索引),但是您可以使用类似以下的方法来处理: / p>

array_column() doesn't maintain indexes (although it allows you to set your own from other data columns in the row), but you can handle that using something like:

array_combine(
    array_keys($myarray),
    array_column($myarray,'columnbeingsearchedhere')
);

编辑

或者,这可能会临时占用更多的内存(除非您不介意修改原始数组),但总体上可能会快一些(取决于数据):

Alternative, that probably grabs a bit more memory temporarily (unless you don't mind the original array being modified), but might be a bit faster overall (depending on your data):

$newArray = $myArray;
array_walk($newArray, function(&$value) use ($columnName) { $value = $value[$columnName]; } );

这篇关于php array_column与不连续的索引返回错误的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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