I want a php algorithm for the following issue - php

I have a multidimensional array like -
array(
"C" => array('A','A1','A2','B',B1'),
"C1" => array('A','A1','A2','B',B1'),
"A" => array('B','B1','C',C1'),
"B1" => array('A','A1','A2','C',C1'),
"B1" => array('A','A1','A2','C',C1'),
"A2" => array('B','B1','C',C1'),
"A1" => array('B','B1','C',C1')
);
I want a script which will assign a value out of the given array for each key,
Result will be like -
C A/A1/A2/B/B1 - A //I can assign any value from A/A1/A2/B/B1
C1 A/A1/A2/B/B1 - A1 //Once A is assigned for the above key then C1 will get value from A1/A2/B/B1 skipping the 'A' which is assigned to key 'C'
A B/B1/C/C1 - B //Now A will get value from B/B1/C/C1
B1 A/A1/A2/C/C1 - A2 //B1 will get value from A2/C/C1
B A/A1/A2/C/C1 - C //Likewise all the values will be assigned uniquely
A2 B/B1/C/C1 - B1
A1 B/B1/C/C1 - C1
The condition is that an the same value will not be assigned to multiple keys i.e all the keys will have different value. (Check the above result to know what exactly needs to be assigned)

$data = array(
"C" => array('A','A1','A2','B','B1'),
"C1" => array('A','A1','A2','B','B1'),
"A" => array('B','B1','C','C1'),
"B1" => array('A','A1','A2','C','C1'),
"B" => array('A','A1','A2','C','C1'),
"A2" => array('B','B1','C','C1'),
"A1" => array('B','B1','C','C1')
);
$assigned = array();
$result = array();
foreach($data as $k => $v) {
for($i=0;$i<count($v);$i++) {
if (!in_array($v[$i],$assigned)) {
$assigned[] = $v[$i];
$result[$k] = $v[$i];
break;
}
}
}
var_dump($result);
output:
array(7) {
["C"]=>
string(1) "A"
["C1"]=>
string(2) "A1"
["A"]=>
string(1) "B"
["B1"]=>
string(2) "A2"
["B"]=>
string(1) "C"
["A2"]=>
string(2) "B1"
["A1"]=>
string(2) "C1"
}
this solution is not good enaugh ;) if you define C1 as array('A') then C1 will be without value, to prevent that you can try to check is there posibility to assign values in different configuration.
$data = array(
"C" => array('A','A1'),
"C1" => array('A'),
"A" => array('B','B1','C','C1'),
"B1" => array('A','A1','A2','C','C1'),
"B" => array('A','A1','A2','C','C1'),
"A2" => array('B'),
"A1" => array('B','B1','C','C1')
);
$assigned = array();
$keys = array_keys($data);
for($i=0;$i<count($keys);$i++) {
getValue($data, $assigned, $keys, $i);
}
function getValue($data, &$assigned, $keys, &$i, $x = null) {
$j = $x === null ? 0 : array_search($x, $data[$keys[$i]]) +1;
for($j; $j<count($data[$keys[$i]]); $j++) {
$v = $data[$keys[$i]][$j];
if(!in_array($v, $assigned)) {
$assigned[$keys[$i]] = $v;
return;
}
}
$i--;
if ($i < 0) {
throw new Exception('no solutions');
}
$val = $assigned[$keys[$i]];
$assigned[$keys[$i]] = null;
getValue($data, $assigned, $keys, $i, $val);
}
var_dump($assigned);

Related

Get lowest key - array value in multidimensional array PHP

So, I got array that looks something like this:
[65]=>
array(2) {
[0]=>
array(2) {
["p"]=>
float(234)
["sp"]=>
float(234)
}
[1]=>
array(2) {
["p"]=>
float(53)
["sp"]=>
float(5)
}
[2]...
[3]...
}
The idea is to go through each of 0 - N values of key 65 array, and only keep one with smallest "p", others should be removed / filtered out.
This should be done in PHP.
Anyone has any idea?
I tried something like this:
$array = array_filter($array, function ($value, $key) use ($a) {
return $a['p'] <= $value['p'];
}, ARRAY_FILTER_USE_BOTH);
where $value is 1 of elements inside 65 keyed-array and $a is current pair that is being added dynamically. So when ever its added, I go through existing elements and if its lowest, it should stay, and others get instant filtered out, but if its higher, it should automatically be filtered out.
Thank you!
You can use array_reduce() to get the lowest "p"-value:
$arr = [
65 => [
["p" => 234, "sp" => 234],
["p" => 53, "sp" => 5],
["p" => 530, "sp" => 5],
]
];
function getLowestKey($carry, $item) {
if ($item['p'] < $carry || !$carry) {
$carry = $item['p'];
}
return $carry;
}
$lowestKey = array_reduce($arr[65], 'getLowestKey');
var_dump($lowestKey); // int(53)
Edit:
I just noticed there is a second part to your question, sorry about that. Once you found out the "lowest p" you can then just filter the array with that knowledge:
$lowestPs = array_filter($arr[65], function($item) use ($lowestKey) {
return $item['p'] == $lowestKey;
});
var_dump($lowestPs);
/*
array(2) {
[1]=>
array(2) {
["p"]=>
int(53)
["sp"]=>
int(5)
}
[2]=>
array(2) {
["p"]=>
int(53)
["sp"]=>
int(5)
}
}
*/
This solution works even if multiple entries have the same lowest "p" value (like 53 in the above example), all of those will stay.
Use array_column() to do an array_multisort() on the 'p' value for the records inside key 65.
<?php
$col = 'p'; // set the column you want to order on
$column = array_column($arr[65], $col);
array_multisort($column, SORT_ASC, $arr[65]);
$arr[65] = $arr[65][0]; // only keep the record with lowest 'p' value
demo
If have more than 1 nested levels, you might also use a recursive approach checking the value of p, keeping the array with the lowest value.
$arrays = [
65 => [
["p" => 234, "sp" => 234],
[
["p" => 53,"sp" => 5],
[
["p" => 54,"sp" => 1],
["p" => 53,"sp" => 7],
]
], [
"p" => 255,
"sp" => 235
],
]
];
function loop($array, &$coll = [], &$min = null)
{
foreach ($array as $key => $value) {
if (is_array($value)) {
loop($value, $coll, $min);
} elseif ($key === "p") {
if ($min === null) $min = $value;
if ($min > $value) {
$coll = [$array];
$min = $value;
continue;
}
if($value === $min) $coll[] = $array;
}
}
return $coll;
}
$arrays[65] = loop($arrays[65]);
var_dump($arrays);
Output
array(1) {
[65]=>
array(2) {
[0]=>
array(2) {
["p"]=>
int(53)
["sp"]=>
int(5)
}
[1]=>
array(2) {
["p"]=>
int(53)
["sp"]=>
int(7)
}
}
}
See another php demo.

Change array keys to specific strings

I am looking for a way to explicitly change some array keys as they will always be the same and the array length will always be the same and then output a single key based on the lowest value. Here is where I am at:
The array code itself look like this:
$t = array($low_score_1,$low_score_2,$low_score_3,$low_score_4,$low_score_5,$low_score_6,$low_score_7,$low_score_8);
Output example:
array(8) { [0]=> string(2) "11" [1]=> string(2) "15" [2]=> string(2) "13" [3]=> string(2) "12" [4]=> string(2) "18" [5]=> string(2) "16" [6]=> string(2) "16" [7]=> string(2) "14" }
So I want to change all 8 keys to each be a specific string. So I need to change the keys and then only output the key of the lowest value in the array. I can only at the moment output the value of the lowest in the array like so:
echo min($t);
And from the array above you can see that 11 is the lowest so that is the one I want to show BUT by ke and not value...
UPDATE
I have managed to set my keys and output both the keys with their retrospective pairs but I just want to show the lowest value by its key.
$t = array(
'a' => $low_score_1,
'b' => $low_score_2,
'c' => $low_score_3,
'd' => $low_score_4,
'e' => $low_score_5,
'f' => $low_score_6,
'g' => $low_score_7,
'h' => $low_score_8,
);
reset($t);
while (list($key, $val) = each($t)) {
echo "$key => $val\n";
}
The output of this looks like:
a => 11 b => 15 c => 13 d => 12 e => 18 f => 16 g => 16 h => 14
As mentioned it's a simple 'find minimum' problem.
Only that you want to save the key of the minimum value.
$t = array($low_score_1,$low_score_2,$low_score_3,$low_score_4,$low_score_5,$low_score_6,$low_score_7,$low_score_8);
//Setting new keys
$t2 = array();
foreach($t as $key => $val){
$key2 = 'score_' . ($key+1);
$t2[$key2] = $val;
}
//Finding the minimum
$min = $t2['score_1'];
$min_key = 0;
foreach($t2 as $key => $val){
if($val < $min){
$min = $val;
$min_key = $key;
}
}
//output
print_r($t2);
echo $min; // the min value
echo $min_key; // the key of the min value

How to group an array into subarrays using its keys?

I am looking to group an array into subarrays based on its keys.
Sample Array
Array
(
[0] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 1
[b_name] => B1
[c_id] => 1
[c_name] => C1
)
[1] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 1
[b_name] => B1
[c_id] => 2
[c_name] => C2
)
[2] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 2
[b_name] => B2
[c_id] => 3
[c_name] => C3
)
[3] => Array
(
[a_id] => 2
[a_name] => A2
[b_id] => 3
[b_name] => B3
[c_id] => 4
[c_name] => C4
)
)
I need this sample array to be converted into a JSON array of the following format:
Expected Output
[{
"a_id": 1,
"a_name": "A1",
"b_list": [{
"b_id": 1,
"b_name": "B1",
"c_list": [{
"c_id": 1,
"c_name": "C1"
}, {
"c_id": 2,
"c_name": "C2"
}]
}, {
"b_id": 2,
"b_name": "B2",
"c_list": [{
"c_id": 3,
"c_name": "C3"
}]
}]
}, {
"a_id": 2,
"a_name": "A2",
"b_list": [{
"b_id": 3,
"b_name": "B3",
"c_list": [{
"c_id": 4,
"c_name": "C4"
}]
}]
}]
I was able to group by a key using the code below.
$array = array(
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "1","c_name" => "C1"),
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "2","c_name" => "C2"),
array("a_id" => "1","a_name" => "A1","b_id" => "2","b_name" => "B2","c_id" => "3","c_name" => "C3"),
array("a_id" => "2","a_name" => "A2","b_id" => "3","b_name" => "B3","c_id" => "4","c_name" => "C4")
);
$return = array();
foreach($array as $val) {
$return[$val["a_id"]][] = $val;
}
print_r($return);
But my actual scenario involves grouping into sub arrays didn't worked.
Looking forward to see if there is an optimized way or useful function to get into my expected JSON response.
Note: I am looking into a generalized use case here . For example : a_list as countries,b_list as states and c_list as cities.
Man that is very specific use case for arrays. Well here is your solution.
$array = <YOUR SAMPLE ARRAY>
$output = [];
/*
* Nesting array based on a_id, b_id
*/
foreach ($array as $item) {
$aid = $item['a_id'];
$bid = $item['b_id'];
$cid = $item['c_id'];
if(!isset($output[$aid])){
$output[$aid] = [
'a_id' => $item['a_id'],
'a_name' => $item['a_name'],
'b_list' => [
$bid => [
'b_id' => $item['b_id'],
'b_name' => $item['b_name'],
'c_list' => [
$cid = [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
]
]
]
]
];
} else if (!isset($output[$aid]['b_list'][$bid])){
$output[$aid]['b_list'][$bid] = [
'b_id' => $item['b_id'],
'b_name' => $item['b_name'],
'c_list' => [
$cid => [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
]
]
];
} else if(!isset($output[$aid]['b_list'][$bid]['c_list'][$cid])) {
$output[$aid]['b_list'][$bid]['c_list'][$cid] = [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
];
} else {
// Do/Dont overrider
}
}
/*
* Removing the associativity from the b_list and c_list
*/
function indexed($input){
$output = [];
foreach ($input as $key => $item) {
if(is_array($item)){
if($key == 'b_list' || $key == 'c_list'){
$output[$key] = indexed($item);
} else {
$output[] = indexed($item);
}
} else {
$output[$key] = $item;
}
}
return $output;
}
$indexed = indexed($output);
print_r(json_encode($indexed, 128));
Interesting requirement there.
Here is my generalized solution that is also extendable.
function transform($array, $group=[
['a_id','a_name','b_list'],
['b_id','b_name','c_list'],
['c_id','c_name'],
]){
foreach($array as $a){
$r = &$result;
foreach($group as $g){
$x = &$r[$a[$g[0]]];
$x[$g[0]] = $a[$g[0]];
$x[$g[1]] = $a[$g[1]];
if(isset($g[2])) $r = &$x[$g[2]]; else break;
}
}
return transformResult($result);
}
function transformResult($result){
foreach($result as &$a)
foreach($a as &$b)
if(is_array($b)) $b = transformResult($b);
return array_values($result);
}
To extend this solution, all you have to do is modify the $group parameter,
either directly in the function declaration or by passing an appropriate value as the 2nd parameter.
Usage example:
echo json_encode(transform($array), JSON_PRETTY_PRINT);
This will return the same output assuming the same $array input in your example.
Now here is the code that works best in the given situation. I have created a similar situation and then explained the solution in detail.
Situation
The Order Form is multipage depending on the number of days served based on the package selected. Details of each package are stored in the database with the following fields:
package_id (Unique Field)
package_name (Name of the Package, e.g. Package A)
servings_count (Total Servings in a Day)
days_served (Number of Days Served in a Month)
In order to carry forward the selection of meals for each day and serving of that day to store as an Order in the database, I required a Multidimensional Array of PHP that can be defined/populated dynamically.
Expected output is something like:
Array
(
[Day 1] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
[Day 2] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
This above array has been created 100% dynamically based on the explained structure and number of servings and days. Below is the code with some explanation.
First, we have to declare two PHP Arrays.
$total_meals_array = []; //Primary, Multidimension Array
$meals_selected_array = []; //Meals Details Array to be used as primary array's key value.
After doing this, run MySQL query to read packages from the database. Now based on the result, do the following:
$total_meals_array = []; //Primary, Multidimension Array
$meals_selected_array = []; //Meals Details Array to be used as primary array's key value.
if( $num_row_packages >= 1 ) {
while($row_packages = mysqli_fetch_array ($result_packages)) {
$package_id = $row_packages['package_id'];
$package_name = $row_packages['package_name'];
$servings_count = $row_packages['servings_count'];
$days_served = $row_packages['days_served'];
//this for loop is to repeat the code inside `$days_served` number of times. This will be defining our primary and main Multidimensional Array `$total_meals_array`.
for ($y = 1; $y <= $days_served; $y++) {
//once inside the code, now is the time to define/populate our secondary array that will be used as primary array's key value. `$i`, which is the meal count of each day, will be added to the key name to make it easier to read it later. This will be repeated `$meals_count` times.
for ($i = 1; $i <= $meals_count; $i++) {
$meals_selected_array["meal_id_" . $i] = "Unique ID";
$meals_selected_array["meal_code_" . $i] = "Meal Name";
$meals_selected_array["meal_type_" . $i] = "Meal";
}
//once our secondary array, which will be used as the primary array's key value, is ready, we will start defining/populating our Primary Multidimensional Array with Keys Named based on `$days_served`.
$total_meals_array["Day " . $y] = $meals_selected_array;
}
}
}
That's it! Our dynamic Multidimensional Array is ready and can be viewed by simply the below code:
print "<pre>";
print_r($total_meals_array);
print "</pre>";
Thank you everyone, specially #yarwest for being kind enough to answer my question.
Here is the code, you can use it for index from a_ to y_ deep. The innerest element is null, if you don't want it. Terminate the for loop before last element, then process last element seperately. You also can do some improvement on this code. Hope this helps.
<?php
$array = array(
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "1","c_name" => "C1"),
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "2","c_name" => "C2"),
array("a_id" => "1","a_name" => "A1","b_id" => "2","b_name" => "B2","c_id" => "3","c_name" => "C3"),
array("a_id" => "2","a_name" => "A2","b_id" => "3","b_name" => "B3","c_id" => "4","c_name" => "C4")
);
$arrays = array_map(function($v){return array_chunk($v, 2, true);}, $array);
$result = [];
foreach($arrays as $value)
{
$ref = &$result;
$len = count($value);
$index = 0;
for(; $index < $len; $index++)
{
$arr = $value[$index];
$char = key($arr)[0];
$charAdd = chr(ord($char)+1);
$key = $arr[$char.'_id'].$arr[$char.'_name'];
$listKey = $charAdd.'_list';
foreach($arr as $k => $v)
{
$ref[$key][$k] = $v;
}
$ref = &$ref[$key][$listKey];
}
}
var_dump($result);
Output: the online live demo
ei#localhost:~$ php test.php
array(2) {
["1A1"]=>
array(3) {
["a_id"]=>
string(1) "1"
["a_name"]=>
string(2) "A1"
["b_list"]=>
array(2) {
["1B1"]=>
array(3) {
["b_id"]=>
string(1) "1"
["b_name"]=>
string(2) "B1"
["c_list"]=>
array(2) {
["1C1"]=>
array(3) {
["c_id"]=>
string(1) "1"
["c_name"]=>
string(2) "C1"
["d_list"]=>
NULL
}
["2C2"]=>
array(3) {
["c_id"]=>
string(1) "2"
["c_name"]=>
string(2) "C2"
["d_list"]=>
NULL
}
}
}
["2B2"]=>
array(3) {
["b_id"]=>
string(1) "2"
["b_name"]=>
string(2) "B2"
["c_list"]=>
array(1) {
["3C3"]=>
array(3) {
["c_id"]=>
string(1) "3"
["c_name"]=>
string(2) "C3"
["d_list"]=>
NULL
}
}
}
}
}
["2A2"]=>
array(3) {
["a_id"]=>
string(1) "2"
["a_name"]=>
string(2) "A2"
["b_list"]=>
array(1) {
["3B3"]=>
array(3) {
["b_id"]=>
string(1) "3"
["b_name"]=>
string(2) "B3"
["c_list"]=>
array(1) {
["4C4"]=>
array(3) {
["c_id"]=>
string(1) "4"
["c_name"]=>
string(2) "C4"
["d_list"]=>
&NULL
}
}
}
}
}
}
This is rather interesting. As far as I can tell, you are trying to transform a flat array into a multidimensional array, as well as transforming the keys into a multidimensional representation.
The top level difference seems to reside in the part before the underscore of the a_* keys.
Then, for each of these keys, every other *_ letters should induce it's own list.
This recursive function does the trick without hardcoding, will work with whatever number of levels, letters (or whatever else) and right identifiers.
It seems to return exactly the json you show in the sample ($array being the array as defined in your question)
$multidimension = multidimensionalify($array, ['a', 'b', 'c'], ['name']);
var_dump(json_encode($multidimension, JSON_PRETTY_PRINT));
function multidimensionalify(
array $input,
array $topLevelLetters,
array $rightHandIdentifiers,
$level = 0,
$parentId = null,
$uniqueString = 'id'
)
{
$thisDimension = [];
$thisLetter = $topLevelLetters[$level];
foreach ($input as $entry)
{
$thisId = $entry["{$thisLetter}_{$uniqueString}"];
$condition = true;
if ($parentId !== null)
{
$parentLetter = $topLevelLetters[$level - 1];
$condition = $entry["{$parentLetter}_{$uniqueString}"] === $parentId;
}
if (!isset($thisDimension[$thisId]) && $condition)
{
$thisObject = new stdClass;
$thisObject->{"{$thisLetter}_{$uniqueString}"} = $thisId;
foreach ($rightHandIdentifiers as $identifier)
{
$thisObject->{"{$thisLetter}_{$identifier}"} = $entry["{$thisLetter}_{$identifier}"];
}
if (isset($topLevelLetters[$level + 1])) {
$nextLetter = $topLevelLetters[$level + 1];
$thisObject->{"{$nextLetter}_list"} = multidimensionalify($input, $topLevelLetters, $rightHandIdentifiers, $level + 1, $thisId, $uniqueString);
}
$thisDimension[$thisId] = $thisObject;
}
}
return array_values($thisDimension);
}
Try this function just pass your array and key name for grouping and then convert to json.
public function _group_by($array, $key) {
$return = array();
foreach ($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}

Slicing two values from array and adding to new array in for loop

I am having issues with a php loop.
Perhaps there is a better way to do this. Currently my post is returning
array(4) {
[1]=> string(2) "on"
["1-qty"]=> string(1) "1"
[5]=> string(2) "on"
["5-qty"]=> string(1) "9"
}
I am trying to make a new array of 2 arrays such as the following
array(2) {
array(2) {
[category]=> string(2) "1"
["qty"]=> string(1) "1"
}
array(2) {
[category]=> string(2) "5"
["qty"]=> string(1) "9"
}
}
I have tried about every foreach and for loop that I can manage to put together. The main problem being the first value I need is the key not the value of the first array. Then I need to take the first two arrays from the main array and add to a new array with the first array key being the new value of the first key category in the array, and the value of the second array being the value of the new key qty in the array, and repeat by groups of 2 foreach set that is in the post variable
Current loop (not working)
$data = $this -> input -> post();
$dCount = count($data);
$newCount = $dCount / 2;
$fin = array();
for ($i = 0; $i <= $newCount; $i++) {
$vals = array_slice($data, 0, $i + 1, true);
$qty = array_slice($vals, 0, $i , true);
$key = current(array_keys($qty));
$final = array('category' => $key, 'qty' => $qty[$key . '-qty']);
$fin[] = $final;
}
Try this way:
$source_arr = array(1 => "on", "1-qty" => 1, 5 => "on", "5-qty" => "9");
$result_arr = array();
foreach ($source_arr as $key => $value) {
if ($value == "on" && isset($source_arr[$key . "-qty"])) {
$result_arr[] = array(
'category' => $key,
'qty' => $source_arr[$key . "-qty"]
);
}
}

how to do the calculation in an array

I have an array :
Array
(
[0] => Array
(
[batch_id] => 1
[seq_id] => 1
[q_id] => 2046
[a1] => 0
[a2] => 1
[a3] => 2
[a4] => 3
[a5] => 4
)
)
I need to minus the value of a1-a5 by 1
desire result(e.g. a1):
array(4) {
["w_id"]=>
string(5) "99911"
["q_id"]=>
string(4) "2046"
["c_id"]=>
string(6) "a1"
["rank"]=>
int(1) "-1"
}
My code is as follow:
$result = mysql_query("Select * from table_1");
while($cr = mysql_fetch_array($result)){
$rr_id = $cr['batch_id'].$cr['seq_id'];
$rid = '999'.$rr_id;
$q_id = $cr['q_id'];
foreach ($cr as $k => $v){
if(preg_match('{^a\d+$}',$k)){
$new_insert[] = array(
'w_id'=>$rid,
'q_id' =>$q_id,
'c_id' =>$k,
'rank'=>$v-1
);
}
}
However, the result of rank becomes
array(4) {
["w_id"]=>
string(5) "99911"
["q_id"]=>
string(4) "2046"
["c_id"]=>
string(6) "a1"
["rank"]=>
int(0)
}
Cannot show the value of rank
Any problem with my code??Can someone answer my question thank you very much
You can use :
$data = array_map(function ($v) {
foreach($v as $k => &$x) {
if (preg_match('{^a\d+$}', $k)) {
$x = $x - 1;
}
}
return $v;
}, $data);
print_r($data);
Live Demo
preg_match('{^Item \d+$}',$k)
You've got wrong pattern inside preg_match (keys you are looking for are 'a1','a2'... not 'item 1', 'item 2'...), just use this one:
preg_match('{^a\d+$}',$k)
Just use loop and pre decrementation
foreach($cr as $k=>&$v)
{
--$v['a1'];--$v['a2'];--$v['a3'];--$v['a4'];--$v['a5'];
}
print_r($cr);
I use $cr as your array.
$cr[] = array("batch_id"=>1, "seq_id"=>1, "q_id"=>'2046', "a1"=>1,"a2"=>1,"a3"=>1,"a4"=>1,"a5"=>1);
foreach($cr as $k=>&$v){
$v['a1'] = $v['a1'] - 1;
$v['a2'] = $v['a2'] - 1;
$v['a3'] = $v['a3'] - 1;
$v['a4'] = $v['a4'] - 1;
$v['a5'] = $v['a5'] - 1;
}
print_r($cr);

Categories