PHP $_POST data into Variable - php

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 ?

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;
}
}

$i = 1;
foreach($_POST as $data) {
${'name_' . $i} = $data["name"];
${'price_' . $i} = $data["price"];
$i++;
}

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.

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>";
}
}
?>

Related

Combine two arrays with just matching override

I have two arrays:
The original:
array(2) {
'app_name' =>
string(15) "dropcat-default"
'site' =>
array(1) {
'environment' =>
array(7) {
'drush_alias' =>
NULL
'backup_path' =>
string(6) "backup"
'config_name' =>
NULL
'original_path' =>
string(33) "/var/www/webroot/shared/some_path"
'symlink' =>
string(43) "/var/www/webroot/mysite_latest/symlink_path"
'url' =>
string(17) "http://localhost"
'name' =>
string(11) "mystagesite"
}
}
}
And the one with overrides:
array(2) {
'app_name' =>
string(17) "dropcat-overrides"
'site' =>
array(1) {
'environment' =>
array(1) {
'drush_alias' =>
string(6) "foobar"
}
}
}
I want to replace the overrides in the original array, but keep the keys that are not present in the override - using array_replace just writes over the existing ones, because I have arrays in arrays. Is there a simple way to solve this?
function _merge_array_rec($arr, $arr2, $i = 0)
{
foreach ($arr2 as $key => $value)
{
if (!isset($arr[$key]))
{
$arr[$key] = $value;
}
else
{
if (is_array($value))
{
$arr[$key] = _merge_array_rec($arr[$key], $arr2[$key], $i + 1);
}
else
{
$arr[$key] = $value;
}
}
}
return $arr;
}
$merge_array = _merge_array_rec($array1, $array2);
array_replace_recursive gets it done for multi dimensional arrays.
As for single dimension arrays, looping through the original array then checking if the overriding array has this value is fun enough.
Something similar to this :
$original=array();
$overriding=array();
foreach($original as $key => $value){
if(isset($overriding[$key]) && !empty($overriding[$key])){
$original[$key]=$overriding[$key];
}
}
Hope this helps
array_key_exists should be used instead of isset, because isset ignores NULL.
The structure of $overrides should be validated, shouldn't it?
Try it out.
<?php
function array_replace_recursive_if_valid(array $defaults, array $overrides) {
foreach ($overrides as $key => $value) {
if (!array_key_exists($key, $defaults)) {
continue;
}
if (is_array($defaults[$key]) && is_array($value)) {
$defaults[$key] = array_replace_recursive_if_valid($defaults[$key], $value);
continue;
}
if (!is_array($defaults[$key]) && !is_array($value)) {
$defaults[$key] = $value;
continue;
}
}
return $defaults;
}
$defaults = [
'app_name' => 'dropcat-default',
'site' => [
'environment' => [
'drush_alias' => null,
'back_path' => 'packup',
'config_name' => null,
'original_path' => '/var/www/webroot/shared/some_path',
'symlink' => '/var/www/webroot/mysite_latest/symlink_path',
'url' => 'http://localhost',
'name' => 'mystagesite',
],
],
];
$overrides = [
'app_name' => 'dropcat-overrides',
'this is invalid' => 'foo',
'site' => [
'environment' => [
'drush_alias' => 'foobar',
'url' => ['this is invalid'],
],
],
];
var_export(array_replace_recursive_if_valid($defaults, $overrides));
In the end, I ended up doing it like this:
$configs = array_replace_recursive($default_config, $env_config);
It covered my use case.

Adding another dimension to array

I have an array of TLDs and prices, and now I want to be able to add a classification i.e. 'Australian','New Zealand','Industry' to the domains but I am having troubles adding the extra dimension.
The array I have is
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$domains = array(
'.com.au' => array(
'country' => 'Australia',
'sector' => 'Industry',
'price' => '19.98'
),
);
Is this a beginning on what you're looking for ?
Is this code ok for you?
<?php
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$newDomains = [];
foreach($domains as $key=>$value){
if($key == '.com.au'){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = 'blabal';
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
?>
Or even:
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$industryArray = array(
'.com.au' => 'blabla'
);
$newDomains = [];
foreach($domains as $key=>$value){
if(isset($industryArray[$key])){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = $industryArray[$key];
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
The result is:
array(5) {
[".com.au"]=>
array(2) {
["TLD"]=>
string(5) "19.98"
["Industry"]=>
string(6) "blabla"
}
[".melbourne"]=>
string(5) "90.00"
[".academy"]=>
string(5) "45.00"
[".accountants"]=>
string(6) "120.00"
[".ac.nz"]=>
string(5) "36.75"
}

Combine array elements

I want to loop through 3 arrays to create 1 single array with all 3 values in them.
See below for example and outcome.
Input:
array(
'0' => array(
'0' => array('a'),
'1' => array('b')
),
'1' => array(
'0' => array('c'),
'1' => array('d'),
'2' => array('e')
),
'2' => array(
'0' => array('f')
),
)
Outcome:
array(
'0' => 'acf',
'1' => 'adf',
'2' => 'aef',
'3' => 'bcf',
'4' => 'bdf',
'5' => 'bef'
)
Funnily I had the same problem a couple of years ago, so here's the solution I then came up with.
public static function combineElementsSuccessive($arry)
{
$result = [];
if (empty($arry) || !is_array($arry)) {
return result;
}
self::concatAndPush('', $result, $arry, 0);
return $result;
}
private static function concatAndPush($str, &$res_arry, $arry, $index)
{
foreach ($arry[$index] as $key => $val) {
$mod_str = $str . $val;
if (isset($arry[$index+1])) {
self::concatAndPush($mod_str, $res_arry, $arry, $index+1);
}
else {
$res_arry[] = $mod_str;
}
}
}
See it in action
Nevermind the static methods, I had to integrate them somehow in an application full of legacy code ;-)
How about this?
// $old_array = your original array
$new_array=array();
for ($i=0; $i<count($old_array[0]); $i++) {
for ($j=0; $j<count($old_array[1]); $j++) {
for ($k=0; $k<count($old_array[2]); $k++) {
$new_array[]=$old_array[0][$i].$old_array[1][$j].$old_array[2][$k];
}
}
}
var_dump($new_array);
It returns:
array(6) { [0]=> string(3) "acf" [1]=> string(3) "adf" [2]=> string(3) "aef" [3]=> string(3) "bcf" [4]=> string(3) "bdf" [5]=> string(3) "bef" }
Convert your array as following numbers array and run the code
$numbers = array(
array("a", "b"),
array("c", "d", "e"),
array("f"),
);
$f_nb = $numbers['0'];
$s_nb = $numbers['1'];
$t_nb = $numbers['2'];
$final_array = array();
for($a = 0; $a<sizeof($f_nb); $a++)
{
for($b = 0; $b<sizeof($s_nb); $b++)
{
for($c = 0; $c<sizeof($t_nb); $c++)
{
$final_array[] = $f_nb["$a"] . $s_nb["$b"] . $t_nb["$c"];
}
}
}
print_r($final_array);
Try this:
$array = array(
'0' => array(
'0' => array('a'),
'1' => array('b')
),
'1' => array(
'0' => array('c'),
'1' => array('d'),
'2' => array('e')
),
'2' => array(
'0' => array('f')
),
);
$outcome = array();
foreach ($array['0'] as $key => $value1)
{
foreach ($array['1'] as $value2)
{
foreach ($array['2'] as $value3)
{
$outcome[] = $value1[0].$value2[0].$value3[0];
}
}
}
print_r($outcome);

Separating array rows into other arrays based on key name

I have an array like this
$rows = array(
array(
'fruit.name' => 'Apple',
'fruit.colour' => 'Red',
'fruit.weight' => '0.1',
'vegetable.name' => 'Carrot',
'vegetable.colour' => 'Orange',
'vegetable.weight' => '0.05'
),
array(
'fruit.name' => 'Banana',
'fruit.colour' => 'Yellow',
'fruit.weight' => '0.7',
'vegetable.name' => 'Potato',
'vegetable.colour' => 'Brown',
'vegetable.weight' => '0.6'
)
);
And i want to be able to sort the array into 2 other arrays called 'fruits' and 'vegetables' based on the first part of the key name so up to the decimal point. With this array I should have 2 rows in each of the fruits and vegetable arrays.
I have this code but it doesn't work and I can't see what I'm doing wrong.
$fruits = array();
$vegetables = array();
foreach($rows as $row)
{
foreach($row as $key => $value)
{
if('fruit' == substr($key, 0, strpos($key, '.')))
{
$fruits[$key] = $row;
}
else
{
$vegetables[$key] = $row;
}
}
}
echo "<pre>"; var_dump($fruits); echo "</pre>";
When i do a var_dump i get this
array(3) {
["fruit.name"]=>
array(6) {
["fruit.name"]=>
string(6) "Banana"
["fruit.colour"]=>
string(6) "Yellow"
["fruit.weight"]=>
string(3) "0.7"
["vegetable.name"]=>
string(6) "Potato"
["vegetable.colour"]=>
string(5) "Brown"
["vegetable.weight"]=>
string(3) "0.6"
}
["fruit.colour"]=>
array(6) {
["fruit.name"]=>
string(6) "Banana"
["fruit.colour"]=>
string(6) "Yellow"
["fruit.weight"]=>
string(3) "0.7"
["vegetable.name"]=>
string(6) "Potato"
["vegetable.colour"]=>
string(5) "Brown"
["vegetable.weight"]=>
string(3) "0.6"
}
["fruit.weight"]=>
array(6) {
["fruit.name"]=>
string(6) "Banana"
["fruit.colour"]=>
string(6) "Yellow"
["fruit.weight"]=>
string(3) "0.7"
["vegetable.name"]=>
string(6) "Potato"
["vegetable.colour"]=>
string(5) "Brown"
["vegetable.weight"]=>
string(3) "0.6"
}
}
Any help please getting this to separate the array into 2 arrays each containing either fruits or vegetables.
This seems to work:
$rows = array(
array(
'fruit.name' => 'Apple',
'fruit.colour' => 'Red',
'fruit.weight' => '0.1',
'vegetable.name' => 'Carrot',
'vegetable.colour' => 'Orange',
'vegetable.weight' => '0.05'
),
array(
'fruit.name' => 'Banana',
'fruit.colour' => 'Yellow',
'fruit.weight' => '0.7',
'vegetable.name' => 'Potato',
'vegetable.colour' => 'Brown',
'vegetable.weight' => '0.6'
)
);
$fruits = $vegs = array();
foreach ($rows as $arrays) {
$fruit = array();
$veg = array();
foreach ($arrays as $key => $val) {
$index = substr($key, strpos($key, ".") + 1);
if('fruit' == substr($key, 0, strpos($key, '.'))){
$fruit[$index] = $val;
} else {
$veg[$index] = $val;
}
}
$fruits[] = $fruit;
$vegs[] = $veg;
}
var_dump($fruits, $vegs);
(Please overlook the fact I've called one of the vars $vegs)
Hope this helps!
I didn't run the code, but it looks like you want:
$fruits[$key] = $value;
-AND-
$vegetables[$key] = $value;

Not getting array all values using php

I have this following array
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
$i=0;
foreach($question as $k=>$v)
{
echo $question[$k]['name'][$i];
$i++;
}
But my output is only
aaaccc
I am missing the value bbb
You need to iterate the inner 'name' arrays - you could use a nested foreach loop:
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
foreach($question as $quest)
{
foreach($quest['name'] as $val)
{
echo $val;
}
}
you should loop though like so
foreach($question as $q)
{
foreach($q['name'] as $v)
{
echo $v;
}
}
in foreach you don't need a counter $i, it's for while() or for()
you array is two dimensional so you need 2 foreach
Check it out in a functional way.
The shorthand array declaration works only on PHP 5.4+ though, but it still works with your longhand array declaration.
$questions = [
'ques_15' => ['name' => ['aaa']],
'ques_16' => ['name' => ['bbb', 'ccc']]
];
array_map(function($a){
foreach ($a['name'] as $v) echo $v;
}, $questions);

Categories