Arrange $_POST to multidimensional array in PHP - php

I have an form when submitting the form and if print $_POST i will get the output like the following
[type] =>'new',
[class] =>'10',
[div] =>c,
[id_228] => 228,
[title_228]=> First,
[colour_228]=> red,
[id_229] => 229,
[title_229]=> second,
[colour_229]=> blue,
[id_230] => 230,
[title_230]=> third,
[colour_230]=> yellow,
[id_231] => 231,
[title_231]=> fourth,
[colour_231]=> orange,
etc
now i have to store this output to an result array . Please see the result array
result_array[1]=array("Title", 'Color')
so in this result array i have to add $_POST like this
result_array[228]=array("First","red")
result_array[229]=array("Second","blue")
result_array[230]=array("Third","yellow")
result_array[231]=array("Fourth","red")
Please help .

First step should be creating a proper looking array out of this data:
https://3v4l.org/r0HZ9
$post = [
'id_228' => 228,
'title_228' => "First",
'colour_228' => 'red',
'id_229' => 228,
'title_229' => "Second",
'colour_229' => 'blue'];
// Transform data into a proper format
$resultArray = [];
foreach($post as $key => $val) {
$key = explode('_',$key);
$resultArray[$key[1]][$key[0]] = $val;
}
// Now do whatever you want to do
var_dump($resultArray);
Now you could add more logic... If you want the data in your proposed format you could do
$result = [];
foreach($resultArray as $item) {
$result[] = [$item['title'], $item['colour']];
}
https://3v4l.org/WC2B0
EDIT:
Since you added
[type] =>'new',
[class] =>'10',
[div] =>c,
you might want to create a list of allowed fields that should be added, maybe something like:
// Transform data into a proper format
$resultArray = [];
$allowedFields = ['id', 'title', 'colour'];
foreach($post as $key => $val) {
$key = explode('_',$key);
if(in_array($key[0], $allowedFields)) {
$resultArray[$key[1]][$key[0]] = $val;
}
}
https://3v4l.org/NQGfa

You'll have to just loop it and prepare a new array.
$result = array();
foreach ($_POST as $key => $value) {
list($title, $key) = explode('_', $key);
if (!is_array($result[$key])) $result[$key] = array();
$result[$key][$title] = $value;
}
var_dump($result);
Hope this helps.

$arr= ["id_228" => 228, "title_228" => "First",
"colour_228"=> "red",
"id_229" => 229,
"title_229"=> "second",
"colour_229"=> "blue",
"id_230" => 230,
"title_230"=> "third",
"colour_230"=> "yellow",
"id_231" => 231,
"title_231"=> "fourth",
"colour_231"=> "orange" ];
foreach($arr as $key => $value) {
$d = explode( '_', $key );
if(true == is_numeric( $value)) {
continue;
}
$c[$d[1]][]= $value ;
}
print_r($c);
Out put
Array
(
[228] => Array
(
[0] => First
[1] => red
)
[229] => Array
(
[0] => second
[1] => blue
)
[230] => Array
(
[0] => third
[1] => yellow
)
[231] => Array
(
[0] => fourth
[1] => orange
)
)

Related

array to array conversion (increase number of dimension and format)

input array
$input = array (
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
needed output form
$target_output = array (
"audi" => array ( "tokyo" => 1, "barcelona" => 2, "paris" => 7 ),
"ford" => array ( "london" => 3, "prag" => 6 )
);
notes 1:
number of groups are dynamic (user input). For example, additional to
"audi" and "ford"; there could be also "toyota", "mercedes".
Each groups has 3 subinfo: 1-name , 2-locations and 3-quantities for
locations.
Sequences in input are always same. 1st name, 2nd locations, 3rd
quantities.
Each group has proper order number always in input. (such as
"group_name_1 or group_locations_4)
notes 2: I've read array functions again. And tried various codes but I even couldn't get close.
Can you please help me.
assuming that group_name_x, group_locations_x and group_quantities_at_locations_x keys alwas exists in your $input array
$input = array(
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
$new_array = array();
foreach ($input as $key => $val) {
if (strpos($key, 'group_name') !== false) {
$new_array[$val] = array();
$group_no = $key[strlen($key) - 1];
$location_array = explode(',', $input["group_locations_{$group_no}"]);
$group_quantities_array = explode(',', $input["group_quantities_at_locations_{$group_no}"]);
$new_array[$val] = array_combine($location_array, $group_quantities_array);
}
}
print_r($new_array);
output:
Array
(
[audi] => Array
(
[tokyo] => 1
[barcelona] => 2
[paris] => 7
)
[ford] => Array
(
[london] => 3
[prag] => 6
)
)
<?php
$inputs = array (
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
$result = array();
foreach ($inputs as $key => $value) {
if (!preg_match('/group_name_([0-9]*)/', $key, $matches)) {
continue;
}
$locations = explode(',', $inputs['group_locations_' . $matches[1]]);
$quantities = explode(',', $inputs['group_quantities_at_locations_' . $matches[1]]);
$result[$value] = array_combine($locations, $quantities);
}
echo '<pre>';
var_dump($result);
echo '</pre>';
You can simply use array_walk like as
$result = [];
$chunked = array_chunk($input,3);
array_walk($chunked,function($v) use (&$result){
$result[$v[0]] = array_combine(explode(",",$v[1]),explode(",",$v[2]));
});
print_R($result);
Demo

How can I compare two Arrays and detect if the values are incorrect or missing?

I have to arrays I would like to compare:
$original and $duplicate.
for example here is my original file:
print_r($original);
Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 )
and here is my duplicate:
print_r($dublicate);
Array ( [0] => cat423 [1] => dug356 )
I compare them with array_diff:
$result = array_diff($original, $dublicate);
My result:
Array ( [1] => dog456 [2] => horse872 [3] => duck082 )
So far so good, but I need to make a difference between the values which are incorrect and the values which are completely missing. Is this possible?
A way would be to crawl the entire original array, afterwards you will have two arrays, missings and duplicates.
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
$missings = $duplicates = array();
foreach ($original as $val) {
if (in_array($val, $duplicate))
$duplicates[] = $val;
else
$missings[] = $val;
}
If you need the keys as well, you would have to alter the foreach loop like so:
foreach ($original as $key=>$val) {
if (in_array($val, $duplicate))
$duplicates[] = array("key" => $key, "value" => $val);
else
$missings[] = array("key" => $key, "value" => $val);
}
use in_array function
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
foreach ($original as $item) {
if(in_array($item, $duplicate))
{
$dup[] = $item;
}
else
{
$miss[] = $item;
}
}
print_r($miss); #Array ( [0] => dog456 [1] => horse872 [2] => duck082 )
print_r($dup); #Array ( [0] => cat423 )
Working Preview

Need some help iterating over this two arrays

I have this two arrays:
$arr1['product_detail'] = array(
"26" => array("Blue", "Green"),
"28" => array("S")
);
$arr2['variation'] = array(
"pupc" => array("123456", "654321"),
"pprice" => array(1, 2),
"pqty" => array(10, 11)
);
I need to build a new array containing values based on position, less said:
$arr3 = array(
array("Blue", "S", "123456", 1, 10),
array("Green", "S", "654321", 2, 11)
);
If you notice I mix all the position of both original arrays. I think in something like:
foreach ($arr2 as $key => $value) {
foreach ($value as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
foreach ($arr1 as $key3 => $value3) {
echo $key3;
}
}
}
}
But it's very ugly and I think is better ways to do this, any help?
It is good idea to use a function
function array_addition($main_array, $new_array) {
foreach ($new_array as $aItem) {
for ($i=0;$i<=1;$i++) {
$main_array[$i][] = current($aItem) ? current($aItem) : reset($aItem);
next($aItem);
}
}
return $main_array;
}
$arr3 = array();
$arr3 = array_addition($arr3, $arr1['product_detail']);
$arr3 = array_addition($arr3, $arr2['variation']);
$arr1['product_detail'] = array(
"26" => array("Blue", "Green"),
"28" => array("S")
);
$arr2['variation'] = array(
"pupc" => array("123456", "654321"),
"pprice" => array(1, 2),
"pqty" => array(10, 11)
);
function convert_array_index_name_to_number($arr)
{
$temp_ar = array();
foreach($arr as $key=>$val)
{
if(is_array($val))
{
$val = convert_array_index_name_to_number($val);
}
$temp_ar[] = $val;
}
return $temp_ar;
}
$arr1 = convert_array_index_name_to_number($arr1);
$arr2 = convert_array_index_name_to_number($arr2);
$arr3 = array();
for($i=0; $i<$count_of_variations; $i++)
{
$temp_arr = array();
$temp_arr[] = $arr1[0][0][$i];
$temp_arr[] = $arr1[0][1][0];
foreach($arr2[0] as $key => $value)
{
$temp_arr[] = $value[$i];
}
$arr3[] = $temp_arr;
}
Result
Array
(
[0] => Array
(
[0] => Blue
[1] => S
[2] => 123456
[3] => 1
[4] => 10
)
[1] => Array
(
[0] => Green
[1] => S
[2] => 654321
[3] => 2
[4] => 11
)
)

Search multidimensional php array by key

I have a multidimensional php array like this
Array
(
[0] => Array
(
[size] => M
[colour] => black
[quantity] => 10
)
[1] => Array
(
[size] => S
[colour] => blue
[quantity] => 10
)
)
and i have another array like this
Array
(
[size] => M
[colour] => black
)
How do i transverse to first array to find the array that matches the second one?.
Am totally clueless on how to go about this. Thanks
Taking a different approach:
$multiArray = array(array('size' => 'M',
'color' => 'black',
'quantity' => '10'),
array('size' => 'S',
'color' => 'blue',
'quantity' => 10));
$otherArray = array('size' => 'S',
'color' => 'blue',
'quantity' => 10)
$message = "Match not found!";
foreach($multiArray as $array) {
$result = array_diff($array, $otherArray);
if(isset($result['size']) or isset($result['color'))
continue;
else
$message = "Found a match!\n Size: {$array['size']}\n Color: {$array['color']}\n Quantity: {$array['quantity']}";
}
echo $message;
This solution seems correct to me because from your example I'm guessing you are trying to find the quantity. Therefore, the array_diff will return the quantity in the result regardless, resulting in the need to check for just size and color for a match.
Consider first array is "mainarray" and second one is "comparearray"
$result = array();
foreach($mainarray as $marray)
{
if($marray['size'] == $comparearray['size'] && $marray['colour'] == $comparearray['colour'])
{
$result = $marray;
//echo "match found";
}
}
note: if compare array is single array it is applicable. if that also multidimension array you should put foreach for that array also.
Try this one
<?php
$arr1 = array(array("size"=>"M","colour" => "black"),array("size"=>"S","colour" => "blue"));
$arr2 = array("size"=>"M","colour" => "black");
print_r($arr1);
print_r($arr2);
foreach($arr1 as $array)
{
if($array['size'] == $arr2['size'] && $array['colour'] == $arr2['colour'])
{
echo "matches";
}
}
?>
working example http://codepad.org/iQPxSHKd
Try
$result = array();
foreach ($multi_array as $arr) {
if ($arr['size'] == $one_dimen_arr['size'] && $arr['colour'] == $one_dimen_arr['colour']) {
$result = $arr;
break;
}
}
For Example:
$array1 is your First array and $array2 is your Second array. Then :
$result = array();
foreach ($array1 as $subarray)
{
$check = array_diff($subarray, $array2);
if (empty($check)) {
$result = $subarray;
}
}

changing keys of a multidimensional array

I have a multidimensional array as shown below. How do I change the keys that start with "id of"?
Array
(
[0] => Array
(
[id of ten] => 1871
[name] => bob
)
[1] => Array
(
[id of nine hundred thousand] => 12581
[name] => barney
)
)
Normally, you'd do something like:
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['old'];
unset($array[$k]['old']);
}
In my case, the key changes dynamically (there are thousands of keys in my multidimensional array and they are random but they will always start w/ "id of...")
thx!
I'm wondering if this is what you are looking for:
<?php
$array = array(
array(
"id of one" => 434,
"name" => "bob"
),
array(
"id of two" => 9323,
"name" => "ted"
)
);
$c_array = count($array);
for ($i = 0; $i < $c_array; $i++)
{
foreach ($array[$i] as $key => $value)
{
if (substr($key, 0, 5) == 'id of') {
$array[$i][substr($key, 6)] = $value;
unset($array[$i][$key]);
}
}
}
print_r($array);
?>
NOTE: Includes use of substr() instead of strpos(). See Gumbo's comment below.
https://ideone.com/xBV5L
This outputs:
Array
(
[0] => Array
(
[name] => bob
[one] => 434
)
[1] => Array
(
[name] => ted
[two] => 9323
)
)
This solution is very clean. Array_shift, does two things at once: returns first element (which has the id), and deletes it from the array, so you can directly assign it to the $new_array at 'id'
$new_arr=array();
foreach ( $array as $arr)
{
$new_arr[array_shift($arr)] = $arr;
}
If the 'id of' key is always the first element of the array, you can use the following:
foreach ($input as &$value)
{
$value['key'] = reset($value);
$key = key($value);
unset($value[$key]);
}
Otherwise, the following worked for me:
foreach ($input as &$value)
{
foreach ($value as $key=>$el) {
if (substr($key, 0, 5) == 'id of') {
$value['key'] = $el;
unset($value[$key]);
}
}
}
In both cases you can change $value['key'] to whatever you want the new key to be.

Categories