我有一个像这样的数组:
[
[
'key1' => 'hello im a text',
'key2' => true,
'key3' => '><><',
],
[
[
'key1' => 'hello another text',
'key2' => 'im a text too',
'key3' => false,
],
[
'key1' = ')(&#',
],
],
[
'key1' => 'and so on',
]
]
如何提取字符串长度为 5 或以上的值并填充平面数组?
想要的结果:
[
1 => 'hello im a text',
2 => 'hello another text',
3 => 'im a text too',
4 => 'and so on',
]
这就是我所做的:
$found = array();
function search_text($item, $key)
{
global $found;
if (strlen($item) > 5)
{
$found[] = $item;
}
}
array_walk_recursive($array, 'search_text');
var_dump($found);
但不知何故它不起作用。
尝试类似的事情:
function array_simplify($array, $newarray=array()) { //default of $newarray to be empty, so now it is not a required parameter
foreach ($array as $i) {
if (is_array($i)) { //if it is an array, we need to handle differently
$newarray = array_simplify($i, $newarray); // recursively calls the same function, since the function only appends to $newarray, doesn't reset it
continue; // goes to the next value in the loop, we know it isn't a string
}
if (is_string($i) && strlen($i)>5) { // so we want it in the one dimensional array
$newarray[] = $i; //append the value to $newarray
}
}
return $newarray; // passes the new array back - thus also updating $newarray after the recursive call
}
我的说明:我还没有测试过这个,如果有错误,请告诉我,我会尽力修复它们。
这样的东西应该有效,
作为我用过的条件
if(is_string($son))
为了获得一些结果,您可以根据自己的喜好进行调整
$input = <your input array>;
$output = array();
foreach($input AS $object)
{
search_text($object,$output);
}
var_dump($output);
function search_text($object, &$output)
{
foreach($object AS $son)
{
if(is_object($son))
{
search_text($son, $output);
}
else
{
if(is_string($son))
{
$output[] = $son;
}
}
}
}
描述:
search_text
获取 2 个参数:$object
和结果数组 $output
。
它检查每个对象的属性是否是对象。
如果是,则需要检查该对象本身,
否则
search_text
检查输入是否是字符串,如果是则存储到 $output
数组中