1

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.

Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
Smilie
  • 13
  • 1
  • 5
  • you need to match keys that have different status or you just want to know if they are identical? –  Oct 05 '11 at 16:46
  • I just need to know if all found arrays have same status value (0 or 1); solution bellow solved my problem :) – Smilie Oct 05 '11 at 17:20

4 Answers4

2

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.
hakre
  • 193,403
  • 52
  • 435
  • 836
  • This ain't working :( $status array contains: Array ( [0] => 1 [1] => 0 [2] => 1 ) So counting it get's me nowhere... – Smilie Oct 05 '11 at 17:17
  • Why does it get you no where? have you looked into `$count` as well? Should work with that `$status` array. Am I missing something? – hakre Oct 05 '11 at 17:38
1
function allTheSameStatus( $data )
{
    $prefStatus = null;
    foreach( $data as $array )
    {
        if( $prefStatus === null )
        {
            $prefStatus = $array[ 'status' ];
            continue;
        }

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

    return true;
}
Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
1

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);
ComFreek
  • 29,044
  • 18
  • 104
  • 156
0

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'];
}
Jasper
  • 75,717
  • 14
  • 151
  • 146