0

I have the following array from $_POST:

array { 
["item"]=> array() { 
    [0]=> "pen" 
    [1]=> "pencil" 
    [2]=> "ruler" 

array { 
["note"]=> array() { 
    [0]=> "permanent" 
    [1]=> "not so permanent" 
    [2]=> "measures stuff" 

array { 
["cost"]=> array() { 
    [0]=> "67.99" 
    [1]=> ".15" 
    [2]=> "1.49"

That I want to combine into single line items, e.g

array { 
["line_items"]=> array() {

["0"]=> array() {
        [item]=> "pen" 
        [note]=> "permanent"
        [cost]=> "67.99"

["1"]=> array() {
        [item]=> "pencil" 
        [note]=> "not so permanent"
        [cost]=> ".15"      

["3"]=> array() {
        [item]=> "ruler" 
        [note]=> "measures stuff"
        [cost]=> "1.49" 

I've had a look at array_merge, array_merge_recursive, array_combine, but all these functions don't do what i'm looking for. I've tried a few different for each and for loops, but I just can't get my head around it.

Please ask if you need more info, this isn't very clear, but like i say, my head - struggling to get around this.

1 Answer 1

2

You'll have to come up with something on your own for this:

$length = count($_POST['item']);
$items = array();
for ($i = 0; $i < $length; $i++) {
    $item = array();
    $item['item'] = $_POST['item'][$i];
    $item['note'] = $_POST['note'][$i];
    $item['cost'] = $_POST['cost'][$i];
    $items[] = $item;
}

var_dump($items);

Should get you what you need. Note that it has no error checking or validation of any kind - you'll want to add that.

Edit: made a stupid mistake in my answer - corrected.

Sign up to request clarification or add additional context in comments.

2 Comments

You are a golden god, thank you so much. Such a quick answer too. got it working perfectly. One day i'll be as good as you. Next time i'm in the pub i'll buy a random person a pint, hopefully it will be you.
@Mason8r Haha - appreciate the compliments. Glad it worked out for you and welcome to Stack overflow!

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.