开发者

Why my php array is over written when they have same Keys

I have a custom PHP function which executes a stored procedure and returns an array:

function test(){
  $in      = array("abc","bcd","efg");
开发者_如何学运维  $result  = mydba->executestoredprocedure('proc1',$in);
  $arr_sim = array();

  foreach ($result['recordset'] as $rows) {
    if (!empty($rows)) {
      echo $arr_sim[$rows['field1']] = $rows['field2'];
    }
  }

  return $arr_sim;
}

In the above function $arr_sim is returning the number of items correctly when the rows["field1"] values are different. If the rows["field1"] values are the same then it is overwriting the first value and returning only the last one. How can I overcome this?

array ( [chicago] => 'sears', [rochester] => 'liberty' )

If the $arr_sim contains these items then it is returned correctly. Because the keys are different.

array ( [chicago] => 'MCD', [chicago] => 'TACOBELL' )

If the $arr_sim contains these items then it is not returned correctly. Because the keys are the same, "chicago".


Array keys must be unique. Instead, do something like this:

// You want the array to look like this
// array('chicago' => array('MCD', 'TACOBELL'));

function test(){
  $in  = array("abc","bcd","efg");
  $result = mydba->executestoredprocedure('proc1',$in);
 $arr_sim=array();
 foreach ($result['recordset'] as $rows) {
  if(!empty($rows)){
    if(array_key_exists($rows['field1'], $arr_sim) {
        $arr_sim[$rows['field1']][] = $rows['field2'];
    } else {
        $arr_sim[$rows['field1']] = array($rows['field2']);
    }
  }
 }
 return $arr_sim;
}


Replace $arr_sim[$rows['field1']] = $rows['field2'] with $arr_sim[$rows['field1']][] = $rows['field2']. This will create an array of arrays.

echo $arr_sim['chicago'][0]; // MCD
echo $arr_sim['chicago'][1]; // TACOBELL

Technically, you should write something like this to avoid notices:

if (!isset($arr_sim[$rows['field1']])) $arr_sim[$rows['field1']] = array();
$arr_sim[$rows['field1']][] = $rows['field2'];

But you must really ask yourself, is the field1 (city names) worthy of being the primary key for the array? If not, you should choose some other identifier.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜