0

I have an array of strings in PHP like this:

people = array("John","Kim");

I want to convert each of those strings into arrays themselves. Basically, I now want a 2-dimensional array like

people(John[],Kim[]);

I've been struggling with the implementation and am not sure how to do it.

5
  • 1
    So you want array('John' => array(), 'Kim' => array())? Commented Mar 18, 2012 at 2:49
  • what do you want those arrays to contain - the letters of the name, like ['j','o','h',n']? Commented Mar 18, 2012 at 2:50
  • So I'm eventually going to have a 4-dimensional array. people[names[purchases[number of that purchase]]]], like people[John[couch[2]]]]. I'm basically implementing a tree using arrays. Commented Mar 18, 2012 at 2:56
  • adding time and space? (4-dimensional is a misnomer - you have 2 dimension over, and down - height, and width. Some complex DBs add a 3rd dimension, time) Commented Mar 18, 2012 at 11:26
  • And even so, people[John[couch[2]]]] is not the best design, try something more meaningful using keys: {john:{purchase="chair",price="100",qty="2"},stephanie:{...} }, OR BETTER YET, use some people, and purchase objects instead. Commented Mar 18, 2012 at 11:32

2 Answers 2

1
$people = array_fill_keys(array("John","Kim"), array());
Sign up to request clarification or add additional context in comments.

Comments

0

Based on your comment, you should be using a combination of keys or values if you want to do this with multi dimensional arrays (which I'm not sure is the best way, but can't say w/o further context).

$people = array(
   "john" => array()
   );

Then when you want to add products, just go like:

$people["john"]["couch"] = 3; // bought 3 times.
$people["john"][$item] = 0; // if you don't know the count yet for whatever reason.  You can always chagne it later the same way.

Now:

 foreach( $people as $person => $purchases ){
    echo UCFirst( $person );
    if( ! empty( $purchases ) ){
       echo ' has bought:<br />';
       foreach( $purchases as $item => $qty ){
          echo $item.' ('.$qty.')<br />';
       }
    }
 }

I would recommend always making your keys either uppercase or lowercase if you are going to use named. Your call though.

If you give us more code / context, there may be much better ways to do this stuff.

1 Comment

I basically have a list of people, and each item they have purchased, and how many of those items they have purchased. I'm outputting that information in csv to use with highcharts.js. A tree made the most sense in my head, but please let me know if there's a better way.

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.