drug95107 2014-06-13 12:18
浏览 32
已采纳

PHP函数验证n级数组元素

I have tried out with the google and tried myself to get done for the below functionality. I need a function that will validate each array element whether it is scalar or not. So i wrote a simple function that will iterate each element of the array and checks for scalar or not.

But the real requirement, the array could be a multi dimentional array. So i have modified the array and called the function recursively as below, But it will not go-through all elements in the array.

function validate_scalar($params)
{
    foreach ($params as $key => $arg)
    {
        if (is_array($arg))
        {
            validate_scalar($arg);
        }
        else
        {
            if (!is_scalar($arg))
            {
                  // throwing an exception here if not scalar.
            }
        }
    }
    return true;
}

Is there any method to achieve this functionality? Please help me on this.

  • 写回答

1条回答 默认 最新

  • douou6807 2014-06-13 12:42
    关注

    array_walk_recursive

    You could use something like this:

    <?php
    
    $array = array(
        'kalle' => 'asdf', 
        'anka' => array(
            123, 
            54324, 
            new stdClass()
        )
    );
    
    array_walk_recursive($array, function ($item, $key) {
        if (!is_scalar($item)) {
            echo $key . " =>  : Is not scalar
    ";
            return false;
        }
        echo $key . " =>  : Is scalar
    ";
        return true;
    });
    

    array_walk_recursive ignores values that are arrays

    output:

    kalle =>  : Is scalar
    0 =>  : Is scalar
    1 =>  : Is scalar
    2 =>  : Is not scalar
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效