Rearrange array - php

I am getting this array when form is submitted
array
'item' =>
array
0 => string 'Salt'
1 => string 'Pepper'
'quantity' =>
array (size=2)
0 => string '2 spoon'
1 => string '5'
and now want to rearrange above array, so it should look like
array
'0' =>
array
'item' => string 'Salt'
'quantity' => string '2 spoon'
'1' =>
array
'item' => string 'Pepper'
'quantity' => string '5'
I tried so many combinations but failed, will somebody help me how to rearrange this array. Any help will be more than appreciated.

Try this
$array = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$new_array = array();
foreach ($array['item'] as $key => $value) {
$new_array[$key]["item"] = $value;
$new_array[$key]["quantity"] = $array['quantity'][$key];
}
echo "<pre>";
var_dump($new_array);

Do it as below -
<?php
$arr=array(
'item' =>
array(
0 => 'Salt' ,
1 => 'Pepper'
),
'quantity' =>
array (
0 =>'spoon',
1 =>'5'
)
);
$result=array();
$com=array_combine($arr['item'],$arr['quantity']);
foreach($com as $k=>$v)
{
$result[]=array("item"=>$k,"quantity"=>$v);
}
print_r($result);
?>
OUTPUT
Array (
[0] => Array ( [item] => Salt [quantity] => spoon )
[1] => Array ( [item] => Pepper [quantity] => 5 )
)

try this, I think this would help you,
$a = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$i = 0;
foreach($a['item'] as $row){
$b[$i]["item"] = $row;
$b[$i]["quantity"] = $a['quantity'][$i];
$i++;
}
print_r($b);
Output from print_r() will be
Array
(
[0] => Array
(
[item] => Salt
[quantity] => 2 spoon
)
[1] => Array
(
[item] => Pepper
[quantity] => 5
)
)

You can simply use array_walk like as
$result = [];
array_walk($arr['item'], function($v, $k)use(&$result, $arr) {
$result[$k]['item'] = $arr['item'][$k];
$result[$k]['quantity'] = $arr['quantity'][$k];
});
print_r($result);
Demo

Hoping that your array is stored in the $array variable and that item is leading. Meaning that there is always an item in the array and not always a quantity
<?php
foreach($array['item'] as $key => $item) {
$newArray[$key]['item'] = $item;
if (isset($array['quantity'][$key]) {
$newArray[$key]['quantity'] = $array['quantity'][$key];
} else {
$newArray[$key]['quantity'] = 0;
}
?>

Related

shift multidimentional array to single array

I want to remove key 0 from parent array and set child array as parent.
Here I will get single value so one array is ok for me.
My current array looks like this
Array
(
[0] => Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
)
I want it like below. expected result
Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
For this I tried like below but no success.
$new = array();
foreach ($data as $v){
$new = array_merge($new , array_values($v)) ;
}
but in my code it's removed key e.g id,api_key, etc....
I need key name also in my new array. please suggest
Remove the array_values
Solution
<?php
$test = array(
array
(
'id' => 3,
'api_key' => 'acount266'
)
);
$new = array();
foreach($test as $v){
$new = array_merge($new, $v);
}
var_dump($new);
Result
array(2) {
["id"]=>
int(3)
["api_key"]=>
string(9) "acount266"
}
According to documentation of PHP as mentioned
reset() function returns the value of the first array element, or
FALSE if the array is empty.
$array = array(
array(
'id' => 3,
'api_key' => 'acount266',
'auth_domain' => 'Tester26',
'database_url' => 'vcc.test.acc+27#gmail.com',
'project_id' => '12345',
'storage_bucket' => '',
'secret_key_path' => '',
'fcm_server_key' => 1,
'messaging_sender_id' => 0,
'key_phrase' => '',
'disable' => 0,
'created' => '',
'updated' => ''
)
);
print_r(reset($test));
I tried this:
$arr = array();
foreach ($examples as $example) {
foreach ($example as $e) {
array_push($arr, $e);
}
}
Don't overcomplicate this, reassigning the first element to the parent array is quick and easy:
<?php
$array =
array (
0 =>
array (
'first' => 'Michael',
'last' => 'Thompson'
)
);
$array = $array[0];
var_export($array);
Output:
array (
'first' => 'Michael',
'last' => 'Thompson',
)
Or:
$array = array_shift($array);

PHP : Concatenate arrays with condition

I'm trying to read a session variable, create arrays and concatenate them :
Session variable sample:
Array
(
[0] => Array
(
[idArticle] => 224
[ntypeArticle] => 1
)
[1] => Array
(
[idArticle] => 556
[ntypeArticle] => 2
)
[2] => Array
(
[idArticle] => 312
[ntypeArticle] => 1
)
)
I need to read this arrays one by one and create arrays by "ntypeArticle".
If ntypeArticle=1, create array1
If ntypeArticle=2, create array2
My code :
$type1 = array();
$type2= array();
$typeAll = array();
foreach($_SESSION['cart'] as $item)
{
if ($item['ntypeArticle'] == 1) {
$type1= array ( "Type" => '1', );
} else {
$type2= array ( "Type" => '2', );
}
array_push($typeAll , $type1 , $type2);
}
But this creates empty arrays.
Wanted output :
Array
(
[0] => Array
(
[type] => 1
)
[1] => Array
(
[type] => 2
)
[2] => Array
(
[type] => 1
)
)
All you need is this simple thing:
$out = [];
foreach($_SESSION['cart'] as $k => $item)
{
$out[$k] = ['Type' => $item['ntypeArticle']];
}
Now if you output $out variable you get what you need.
Try This
$newOp1 = array()
$newOp2 = array()
foreach($_SESSION['cart'] as $item){
if($item["ntypeArticle"] == 1){
$newOp1[]['type'] = $item["ntypeArticle"]
}else{
$newOp2[]['type'] = $item["ntypeArticle"]
}
}
print_r($newOp1);
print_r($newOp2);
Basing on information you provided, all you want to do is to extract nTypeArticle as type element. That's all.
//array from your example
$inputArray = array(
array(
'idArticle' => 224,
'nTypeArticle' => 1
),
array(
'idArticle' => 556,
'nTypeArticle' => 2
),
array(
'idArticle' => 312,
'nTypeArticle' => 1
),
);
$outputArray = array_map(function($inputElement) {
return array('type' => $inputElement['nTypeArticle']);
}, $inputArray);
var_dump($outputArray);
//Output (the same as yours):
//array (size=3)
// 0 =>
// array (size=1)
// 'type' => int 1
// 1 =>
// array (size=1)
// 'type' => int 2
// 2 =>
// array (size=1)
// 'type' => int 1
$output = new array();
$input = array(
array(
"idArticle" => 224,
"nTypeArticle" => 1
),
array(
"idArticle" => 556,
"nTypeArticle" => 2
),
array(
"idArticle" => 312,
"nTypeArticle" => 1
)
);
foreach($input as $article) {
array_push($output, new array("type"=>$article["nTypeArticle"]));
}
print_r($output);
This gives you the thing you asked for.
(Code has been not tested)

Get sum of values which have same value for key php array

I have below array,
Array ( [0] => Array ( [report_id] => 1 [amount] => 100.00 [category_name] => Trial1 ) [1] => Array ( [report_id] => 1 [amount] => 150.00 [category_name] => Trial2 ) [2] => Array ( [report_id] => 1 [amount] => 200.00 [category_name] => Trial2 )
What i want to send to have JSON with below format
It will get some of Equal category name and then send it as json.
[{'category_name': 'Trial1', 'Sum':100]}, {'category_name':'Trial2', 'Sum':350]
How can i achieve this?
Was thinking to get foreach loop and then make compare of category_name and use .=+ to get sum? but i lost there,
Thanks,
Try below solution:
<?php
$array = array (
'0' => Array ( 'report_id' => 1, 'amount' => '100.00', 'category_name' => 'Trial1' ) ,
'1' => Array ( 'report_id' => 1, 'amount' => '150.00' ,'category_name' => 'Trial2' ),
'2' => Array ( 'report_id' => 1, 'amount' => '200.00' ,'category_name' => 'Trial2' ) ,
);
$new_array = array();
foreach($array as $a){
if(!isset($new_array[$a['category_name']]['amount'])){
$new_array[$a['category_name']]['amount'] = 0;
}
$new_array[$a['category_name']] = array(
'category_name' => $a['category_name'],
'amount' => $new_array[$a['category_name']]['amount'] + $a['amount'],
);
}
//print_r(array_values($new_array));
echo json_encode(array_values($new_array));
Output
[{"category_name":"Trial1","amount":100},{"category_name":"Trial2","amount":350}]
Possible solution:
$categoriesArray = array();
foreach ($yourArray as $arrayItem) {
if (!isset($categoriesArray[$arrayItem['category_name']])) {
$categoriesArray[$arrayItem['category_name']] = array(
'category_name' => $arrayItem['category_name'],
'sum' => 0
);
}
$categoriesArray[$arrayItem['category_name']]['sum'] += $arrayItem['amount'];
}
$categoriesArray = json_encode(array_values($categoriesArray));
Assuming $input is your array and $output is the JSON string:
$categorysum = [];
array_walk($input, function($el) use (&$categorysum) {
$categorysum += [$el['category_name'] => ['category_name' => $el['category_name'], 'Sum' => 0]];
$categorysum[$el['category_name']]['Sum'] += $el['amount'];
});
$output = json_encode(array_values($categorysum));

PHP Imploding Multidimensional Array

I need to implode an multi-dimensional array in a string using implode, i tried using the array_map shown here: stackoverflow.com but i failed.
Array:
Array (
[0] => Array (
[code] => IRBK1179
[qty] => 1
)
[1] => Array (
[code] => IRBK1178
[qty] => 1
)
[2] => Array (
[code] => IRBK1177
[qty] => 1
)
)
Desired Output:
IRBK1179:1|IRBK1178:1|IRBK1177:1
Use foreach and implode() inner array with : and then implode() new array with |. Try below code.
$arr = Array (
0 => Array ( 'code' => 'IRBK1179','qty' => 1 ),
1 => Array ( 'code' => 'IRBK1178','qty' => 1 ),
2 => Array ( 'code' => 'IRBK1177','qty' => 1 ) );
$newArr = array();
foreach ($arr as $row)
{
$newArr[]= implode(":", $row);
}
echo $finalString = implode("|", $newArr);
Output
IRBK1179:1|IRBK1178:1|IRBK1177:1
Working Online Demo: Click Here
Use explode() to get back array from string.
Try below code.
$finalString = "IRBK1179:1|IRBK1178:1|IRBK1177:1";
$firstArray = explode("|", $finalString);
foreach($firstArray as $key=>$row)
{
$tempArray = explode(":", $row);
$newArray[$key]['code'] = $tempArray[0];
$newArray[$key]['qty'] = $tempArray[1];
}
print_r($newArray);
Output
Array
(
[0] => Array
(
[code] => IRBK1179
[qty] => 1
)
[1] => Array
(
[code] => IRBK1178
[qty] => 2
)
[2] => Array
(
[code] => IRBK1177
[qty] => 1
)
)
Working Demo : Click Here
As i commented out, use the implode and foreach. for inner array use : and for outer array use |.
$str = array();
foreach($arr as $val){
$str[] = implode(":", $val);
}
echo implode("|", $str); //IRBK1179:1|IRBK1178:1|IRBK1177:1
Both other answers given by Frayne and Ruchish are correct.
Here is another alternative using array_map.
$arr = [[ 'code' => 'IRBK1179','qty' => 1 ],
[ 'code' => 'IRBK1178','qty' => 1 ],
[ 'code' => 'IRBK1177','qty' => 1 ]];
echo implode('|', array_map(function ($val) {
return $val['code'].':'.$val['qty'];
}, $arr));
Output:-
IRBK1179:1|IRBK1178:1|IRBK1177:1
Simple solution using array_reduce function:
// $arr is the initial array
$result = array_reduce($arr, function($a, $b){
$next = $b['code'].":".$b['qty'];
return (!$a)? $next : (((is_array($a))? $a['code'].":".$a['qty'] : $a)."|".$next);
});
print_r($result);
The output:
IRBK1179:1|IRBK1178:1|IRBK1177:1
Here is my version:
<?php
$arr = [
0 => ['code' => 'IRBK1179', 'qty' => 1],
1 => ['code' => 'IRBK1178', 'qty' => 1],
2 => ['code' => 'IRBK1177', 'qty' => 1],
];
$str = implode("|", array_map(function ($value) {return implode(":", array_values($value));}, array_values($arr)));
var_dump($str); # "IRBK1179:1|IRBK1178:1|IRBK1177:1"
$array = array (
'0' => array (
'code' => 'IRBK1179',
'qty' => '1'
),
'1' => array (
'code' => 'IRBK1178',
'qty' => '1'
),
'2' => array (
'code' => 'IRBK1177',
'qty' => '1'
)
);
$string ='';
foreach($array as $key=>$value){
$string .= $value['code'].':'.$value['qty'].'|';
}
echo $string;

count the times a certain key name shows up in a multi-array?

How may I count the times a key shows up in a multi-array?
In the below example, weight should return 2, and reps 4. Does PHP have a built-in function for this?
[0] => Array
(
[0] => Array
(
[weight] => 317.51474856007
[reps] => 10
)
[1] => Array
(
[weight] => 50
[reps] => 10
)
[2] => Array
(
[reps] => 10
)
[3] => Array
(
[reps] => 10
)
)
you can try something like this:
function counter($array){
$result = array();
foreach($array as $key=>$value){
foreach($value as $name => $val){
$result[$name][]=$val;
}
}
return array('all'=>$result,'count weight'=>count($result['weight']),'count reps'=>count($result['reps']));
}
$array= Array(
'0' => Array
(
'weight' => 317.51474856007,
'reps' => 10
),
'1' => Array
(
'weight' => 50,
'reps' => 10
),
'2' => Array
(
'reps' => 12
),
'3' => Array
(
'reps' => 10
)
);
$resp = counter($array);
var_dump($resp);
Try this one liner using array_walk_recursive():
Given your array, $arr
array_walk_recursive($arr, function($v, $k)use(&$count){if(array_key_exists($k, $count))$count[$k]++;else $count[$k]=1;},$count=array());
print_r($count);
See demo
or the old fashioned way:
$count = array();
foreach ($arr as $ar){
foreach ($ar as $k=>$v){
if (array_key_exists($k, $count)){
$count[$k]++;
}
else{
$count[$k] = 1;
}
}
}
print_r($count);
See demo
Output:
Array
(
[weight] => 2
[reps] => 4
)
you can try this:
$array= Array(
'0' => Array
(
'weight' => 317.51474856007,
'reps' => 10
),
'1' => Array
(
'weight' => 50,
'reps' => 10
),
'2' => Array
(
'reps' => 10
),
'3' => Array
(
'reps' => 10
)
);
$weight=0;
$reps=0;
//print_r($array);
foreach($array as $key=>$val){
if(isset($val['weight'])){
echo $val['weight']."<br>";
$weight++;
}
if(isset($val['reps'])){
echo $val['reps']."<br>";
$resp++;
}
}
echo $weight." ".$resp;

Categories