1

I have a script to produce some data that gets pulled into a line graph. I need to produce one line per each company which goes with the $teamCount variable. Right now the script is only creating one array and sticking all of the lines for each company within a single array, which essentially is creating year over year data (which it shouldn't).

I'm unsure how to do this whether I nest a foreach or another for loop.

Here is the script:

      $finance = array(
        array(
            'key' => $companyName,
            'values' => array()
        )
      );

      for ($i = 0; $i < $teamCount; ++$i) {                 
          $count = $i + 1;
          $companyName = 'Company ' . $count;
          $finance[0]['values'][] = array('x' => $count, 'y' => 25000000);
        }

        $insertdata['finance'] = $finance;  

Here is the data output:

array (
  0 => 
  array (
    'key' => 'Company 2',
    'values' => 
    array (
      0 => 
      array (
        'x' => 1,
        'y' => 25000000,
      ),
      1 => 
      array (
        'x' => 2,
        'y' => 25000000,
      ),
    ),
  ),
)

The desired output that I'm unsure of how to do is:

array (
  0 => 
  array (
    'key' => 'Company 1',
    'values' => 
    array (
      0 => 
      array (
        'x' => 1,
        'y' => 25000000,
      ),
    ),
  ),
  1 => 
  array (
    'key' => 'Company 2',
    'values' => 
    array (
      0 => 
      array (
        'x' => 1,
        'y' => 25000000,
      ),      
    ),
  ),
)

1 Answer 1

2

It's only creating one array because you're pushing onto $finance[0] each time through the loop, rather than onto $finance itself. You're setting the $companNname variable, but not putting it anywhere in the array.

$finance = array();
for ($i = 1; $i <= $teamcount; $i++) {
    $finance[] = array(
        'key' => 'Company ' . $i,
        'values' => array(
            array('x' => 1, 'y' => 2500000)
        )
    );
}

$insertdata['finance'] = $finance;
Sign up to request clarification or add additional context in comments.

2 Comments

Yep now that I see it that's pretty easy. Thanks for the help.
there was a small issue, the ; after the $i on the Company name line causes an issue, should be an ,.

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.