0

I have following $_POST data from the form fieldset

array(2) { 
   ["item-1"] => 
       array(2) { 
           ["name"]=> string(5) "apple" 
           ["price"]=> string(1) "5" 
       } 
   ["item-2"] => 
       array(2) { 
           ["name"]=> string(6) "orange" 
           ["price"]=> string(1) "2" 
       }
} 

I want to store this post data into variables using foreach such as $name_1 $price_1 & $name_2 $price_2

How can I parse this form-data ?

2
  • 3
    This seems like a really bad idea, because you may have an unknown number of entries. What exactly is your use-case? Why do you want the variables $name_1, $name_2, etc.? Commented Jan 7, 2015 at 11:53
  • Use an array instead using variables like this. Commented Jan 7, 2015 at 11:59

4 Answers 4

2

Altough I think it's completely unlogical to use variables this way, this can help you out. It created the variables automatically using the given information..

//array with values
$source = [
    'item-1' => [
        'name' => 'apple',
        'price' => '5',
    ],
    'item-2' => [
        'name' => 'orange',
        'price' => '2'
    ]
];

foreach($source as $k=>$array) {
    //get all integer values from the key
    $int = preg_replace('/[^0-9]/', '', $k);

    //foreach property in $array, create the variable name + the integer number 
    //as a variable and set the value belonging to the key
    foreach($array as $name=>$value) {
        ${$name . '_' . $int} = $value;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually this is answer that reflects question the best imo.
0
$i = 1;
foreach($_POST as $data) {
    ${'name_' . $i}  = $data["name"];
    ${'price_' . $i} = $data["price"];
    $i++;
}

Comments

0
foreach ($_POST as $k => $v) {
  $i = +preg_replace('/item-(\d+)/', '$1', $k);
  foreach(array('name', 'price') as $name) {
    $key = "$name_$i";
    $$key = $v[$name];
}

Hope it helps.

Comments

0

Try this..

<?php
$response = 
array(    
        'item-1' => array(
            2 => array(
                'name' => 'apple',
                'price' => 5
            ),          
        ),
        'item-2' => array(
            2 => array(
                'name' => 'orange',
                'price' => 2
            ),          
        ),
    );



foreach($response as $key =>$value)
{

$k=explode("-",$key);
$keyvalue=end($k);
foreach($value as $result)
{
echo ${'name_' . $keyvalue}=$result['name'];
echo "</br>";
echo ${'price_' . $keyvalue}=$result['price'];
echo "</br>";
}
}
?>

Comments

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.