开发者

PHP - how to compare value of arrays in dynamic way?

Ok, I have following 'challange';

I have array like this:

Array
(
    [0] => Array
        (
            [id] => 9
            [status] => 0
        )

    [1] => Array
        (
            [id] => 10
            [status] => 1
        )

    [2] => Array
        (
            [id] => 11
            [status] => 0
        )
)

What I need to do is to check if they all have same [status]. The problem is, that I can have 2 or more (dynamic)开发者_运维百科 arrays inside.

How can I loop / search through them?

array_diff does support multiple arrays to compare, but how to do it? :( Which ever loop I have tried, or my Apache / browser died - or I got completely bogus data back.


You could just put the problem apart to make it easier to solve.

First get all status items from your array:

$status = array();
forach($array as $value)
{
    $status[] = $value['status'];
}

You now have an array called $status you can see if it consists of the same value always, or if it has multiple values:

$count = array_count_values($status);
echo count($count); # number of different item values.


Try this code:

$status1 = $yourArray[0]['status'];
$count = count($yourArray);
$ok = true;

for ($i=1; $i<$count; $i++)
{
  if ($yourArray[$i]['status'] !== $status1)
  {
    $ok = false;
    break;
  }
}

var_dump($ok);


function allTheSameStatus( $data )
{
    $prefStatus = null;
    foreach( $data as $array )
    {
        if( $prefStatus === null )
        {
            $prefStatus = $array[ 'status' ];
            continue;
        }

        if( $prefStatus != $array[ 'status' ] )
        {
            return false;
        }
    }

    return true;
}


I'm not sure what you want as output but you could iterate through the outer array and create an output array that groups the inner arrays by status:

$outputArray = array();
foreach ($outerArray as $an_array) {
    $outputArray[$an_array['status']][] = $an_array['id'];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜