0

I want to dynamically create arrays of arrays and I have no clue how to initialize my arrays...

Here is the code:

$resT= array();
$resR= array();
foreach ($cursor as $obj) {
   if ($obj == NULL) continue;
   $c="XX";
   if (test1)         $c=$obj['GC'];
   array_push($resT[$c],$obj['AT']);
   array_push($resR[$c],$obj['AR']);
}

I got this: array_push() expects parameter 1 to be array

Thanks,

Amir.

2
  • 1
    You should use other variable names: $resT, $resR, $obj and so on are not very useful names. A variable name should always speak for itself. Commented Jul 19, 2011 at 21:17
  • What exactly are you trying to accomplish with this code? Commented Jul 19, 2011 at 21:21

4 Answers 4

2
$resT= array();
$resR= array();
foreach ($cursor as $obj) {
   if ($obj == NULL) continue;
   $c="XX";
   if (test1)         $c=$obj['GC'];
    if(!isset($resT[$c]))
      $resT[$c] = array();
    if(!isset($resR[$c]))
      $resR[$c] = array();
   array_push($resT[$c],$obj['AT']);
   array_push($resR[$c],$obj['AR']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It worked... I am newbie... I didn't know about isset() function.
1

You don't even need to use array_push.

You can use the shorthand notation of

$resT= array();
$resR= array();
foreach ($cursor as $obj) {
   if ($obj == NULL) continue;
   $c="XX";
   if (test1)         $c=$obj['GC'];
   $resT[$c] = array();
   $resT[$c][] = $obj['AT'];
   $resR[$c] = array();
   $resR[$c][] = $obj['AR'];
}

1 Comment

You re-create $resT[$c] ($resR[$c] respectively) in every iteration. This means every $resT[$c] contains only the last element for every value of $c.
0

I have no idea what you're trying to accomplish but this should resolve your PHP notice at least:

$resT= array();
$resR= array();
foreach ($cursor as $obj) {
   if ($obj == NULL) continue;
   $c="XX";
   if (test1)         $c=$obj['GC'];

   if(!is_array($resT[$c])){
      $resT[$c] = array();
   }

   if(!is_array($resR[$c])){
      $resR[$c] = array();
   }

   array_push($resT[$c],$obj['AT']);
   array_push($resR[$c],$obj['AR']);
}

Comments

0
$resT= array();
foreach ($cursor as $obj) {
  if (!is_null($obj)) {
    $c = $test1 ? $obj['GC'] : "XX";
    if (!array_key_exists($c, $resT)) $resT[$c] = array();
    $resT[$c][] = $obj['AT'];
  }
}
$resR = $resT;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.