假设我有一个数组
array
array
key1 = 'hello im a text'
key2 = true;
key3 = '><><';
array
array
key1 = 'hello another text'
key2 = 'im a text too'
key3 = false;
array
key1 = ')(&#'
array
key1 = 'and so on'
如何从上述数组中获取如下所示的内容?
数组 1 => "你好,我是一条短信"; 2 => '你好另一个文本; 3 => "我也是文本"; 4 => "等等";
这是我所做的
$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
数组中