当前位置: 动力学知识库 > 问答 > 编程问答 >

php - A more elegant solution for dealing with a single input for when array of arrays is missing keys

问题描述:

I have the following SQL data pull format available to me stored in the variable $data.

YEAR QUARTER CAT NAME ASSMT_TOTAL

2011 Q2 2011-Q2 Place-1 18

2011 Q3 2011-Q3 Place-1 22

2011 Q4 2011-Q4 Place-2 34

2011 Q3 2011-Q3 Place-2 21

2011 Q4 2011-Q4 Place-2 23

I'm trying to build an "final" array that will contain an array of arrays. Each array will look like this:

[name] => Place-1

[type] => line

[data] => Array

(

[0] => 18

[1] => 22

...

)

I've done the vast majority of it, but I'm struggling for the very few occasions where a place doesn't have a record for that particular category.

$names is an array of all the places and $cats is an array of all the available category names (2011-Q2).

 foreach($names as $s)

{

foreach($cats as $c)

{

$temp['name'] = $s;

$temp['type'] = 'line';

foreach($data as $d)

{

if($s === $d['NAME'] && $c === $d['CAT'])

{

$temp['data'][] = (int)$d['ASSMT_TOTAL'];

break;

}

//$temp['data'][] = 0;

}

}

$final[] = $temp;

unset($temp);

}

The above works well, except for dealing with those odd times that a site doesn't have a corresponding category. For example in my sample data, place-2 doesn't have a CAT for 2011-Q2. How would I insert a zero in this case. I also wondered about a more elegant solution for the double for loop situation.

网友答案:

Since you allready have a list of $cats you can compare your row category (I assume $d['CAT']) against that array and make it a corner case.

$catFoundMarker = false;
foreach($data as $d)
{
    if($s === $d['NAME'] && $c === $d['CAT'])
    {
          $temp['data'][] = (int)$d['ASSMT_TOTAL'];
          $catFoundMarker = true;
          break;
    }
}
if(!$catFoundMarker){
    $temp['data'][] = 0;
}

You can create a similar corner case for when 'NAME' is not there.

EDIT: sorry, updates a mistake in in_array function EDIT2: updated solution

分享给朋友:
您可能感兴趣的文章:
随机阅读: