3 Replies - 953 Views - Last Post: 22 December 2012 - 11:46 AM Rate Topic: -----

#1 makamo66  Icon User is offline

  • New D.I.C Head

Reputation: -5
  • View blog
  • Posts: 42
  • Joined: 04-February 09

Flatten a multidimensional array without recursion

Posted 22 December 2012 - 07:42 AM

This is the meal planner app I'm still working on. I've gotten a lot of useful help so far. You can see the view source at http://maureenmoore....sts/122212.html

I am using the following in my process.php (which the jquery form gets submitted to)
$stack = array();

foreach ($_REQUEST as $key => $value) {
			array_push($stack,$value);
          }
$stack = array_values($stack);

print_r($stack);

$comma_separated = implode(",", $stack);

echo "\n\n" . $comma_separated . "\n\n";


When I click the submit button at localhost it shows an error for array to string conversion because it's a multidimensional array. How can I get rid of the first null key without resorting to a recursive function? I don't see the error any more now that I've uploaded it to my hosting account but it's not printing a comma-separated list because it's a multidimensional array with a key of null.

Is This A Good Question/Topic? 0
  • +

Replies To: Flatten a multidimensional array without recursion

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3712
  • View blog
  • Posts: 5,963
  • Joined: 08-June 10

Re: Flatten a multidimensional array without recursion

Posted 22 December 2012 - 08:02 AM

Why don't you want to use a recursive function? Seems like that would be the solution to your problem.

By the way, a quote from the PHP manual entry for array_push:

Quote

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.


Also, your call to array_values() is redundant. The $stack array is already a numerically indexed array.

O, and one more thing. Why do you specifically create a variable for the $key in your foreach loop, when you don't seem to need to use it at all?
Was This Post Helpful? 1
  • +
  • -

#3 makamo66  Icon User is offline

  • New D.I.C Head

Reputation: -5
  • View blog
  • Posts: 42
  • Joined: 04-February 09

Re: Flatten a multidimensional array without recursion

Posted 22 December 2012 - 11:26 AM

Using $_REQUEST['data'] as suggested by jeroen at stack overflow solved the problem.
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10386
  • View blog
  • Posts: 38,434
  • Joined: 27-December 08

Re: Flatten a multidimensional array without recursion

Posted 22 December 2012 - 11:46 AM

Using $_REQUEST isn't good practice, as it is vulnerable to cookie injection attacks. Stick with either $_GET, $_POST, or $_COOKIE based on what you are using.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1