• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 376
  • Last Modified:

Dynamically created key pair php

I have a foreach loop and need to dynamically create the key value pairs and build the array.  
After running the foreach loop, it should produce something like

  $sampleArray = array(
      'firstfield' => (string)"Person",
     'thirdfield' => (integer)'Quantity',
     'fourthfield' => (string)'Product'
  );

Open in new window


I need to know how to use foreach loop and build the sample array like above
0
debbieau1
Asked:
debbieau1
  • 2
  • 2
1 Solution
 
Chris StanyonCommented:
Not sure what you mean - you need something to loop through with the foreach loop (such as an array)

What exactly do you want to run the foreach loop on?
0
 
debbieau1Author Commented:
Hi Chris

I have values coming from a database table and I need to save these into another table.  

 I have a foreach loop which iterates through.  I want to merge these so it looks like the sample below.  I had problems with each (key value pair replacing, rather than combining them into one array  

       foreach($test as $k=>$sampleEntry)
      {

the key value pair was in here  
      }
      

The goal is to combine the ones from the loop into one array like below.  

$sampleArray = array(
      'firstfield' => (string)"Person",
     'thirdfield' => (integer)'Quantity',
     'fourthfield' => (string)'Product'
  );

Then i will save the $sampleArray to db.  

I hope I am being clear enough.  Please let me know if not.  Thank you very much.
0
 
Chris StanyonCommented:
Without seeing data or code it's difficult to guess what you need, but if you want to add new values to an array in a loop then you need to include the square brackets to indicate it's a new element within the array, otherwise you'll just overwrite what you already have:

Here's an idea for you to play with:

$sampleArray = array();

foreach($test as $k=>$sampleEntry):
   $sampleArray[$k] = $sampleEntry;
endforeach;

var_dump($sampleArray);

Open in new window

0
 
debbieau1Author Commented:
Thanks very much for such a quick and clear response.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now