add item array in a exist array php [duplicate] - php

This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 4 months ago.
I need to add an item array in a exist array. When i try to add i get something like this, using array_push
Array
(
[0] => Array
(
[totalp] => 3.26
[mes] => Novembro
)
[1] => Array
(
[totalp] => 2.66
[mes] => Dezembro
)
[2] => Array
(
[0] => Array
(
[bonus] => 2.6
)
[1] => Array
(
[bonus] => 4.16
)
)
)
but i need this.
Array (
[0] => Array
(
[totalp] => 3.26
[mes] => Novembro
[bonus] => 2.6
)
[1] => Array
(
[totalp] => 2.66
[mes] => Dezembro
[bonus] => 4.16
) )
follow my code.
$arrRows = array();
while ($dados = $resultp ->fetch_array(MYSQLI_ASSOC)) {
$arrRows[] = $dados;//getting totalp and mes here
}
$arrRows1 = array();
while ($dados = $resultb ->fetch_array(MYSQLI_ASSOC)) {
$arrRows1[]=$dados; //getting bonus here
}
array_push($arrRows,$arrRows1); // first example, but i dont need this way.
print_r($arrRows);
thankyou

Use array_map
$res = array_map('array_merge', $arrRows, $arrRows1);
demo

<?php
$newdata = array (
0 => array('totalp'=>'3.26','mes' => 'Novembro'),
1 => array('totalp'=>'2.66','mes' => 'Dezembro')
);
foreach($newdata as $key => $value){
$newdata[$key]['Bonus'] = "12";
}
echo '<pre>';
print_r($newdata);
Check it On LIVE DEMO

Here is code that add bonus in multidimensional array
<?php
$array = array(
array(
"totalp" => "3.26",
"mes" => "Novembro"
),
array(
"totalp" => "3.26",
"mes" => "Novembro"
)
);
for ($i=0; $i < sizeof($array); $i++) {
$array[$i]['bonus'] = "2.2"; // here is you can get output from another array or variable
}
echo "<pre>";
print_r($array);
?>
See Output

Try this,
foreach($arrRows as $key=>$row){
$arrRows[$key]['bonus'] = $arrRows1[$key]['bonus'];
}
echo "<pre>";
print_r($arrRows);
echo "</pre>";

Use array merge like below code snippet:
$out = array();
foreach ($arrRows as $key => $value){
$out[] = array_merge((array)$arrRows1[$key], (array)$value);
}
print_r($out);
You can check this url for reference: Array merge on multidimensional array

Related

codeigniter modify array from string for insert_batch

This is my form input $data, i want this keep this input.
$data = "39X3,29X5";
this my code convert string to array
$data = explode(",", $data);
$out = array();
$step = 0;
foreach($data as $key=>$item){
foreach(explode('X',$item) as $value){
$out[$key][$step++] = $value;
}
print '<pre>';
print_r($out);
print '</pre>';
result
Array
(
[0] => Array
(
[0] => 39
[1] => 3
)
[1] => Array
(
[2] => 29
[3] => 5
)
)
but i want change the keys and fix this for support query builder class
$this->db->insert_batch('mytable',$out).
Like this.
array
(
array
(
'number' => 39
'prize' => 3
),
array
(
'number' => 29
'prize' => 5
)
)
i try hard and confuse using loop.
So you need to remove inner foreach and put relevant values into array.
foreach($data as $key=>$item){
$exp = explode('X', $item);
$out[$key] = [
'number' => $exp[0],
'prize' => $exp[1]
];
}
Check result in demo
change your foreach loop to the following:
foreach($data as $key=>$item){
$temp = explode('X',$item);
$out[] = ['number' => $temp[0] , 'prize' => $temp[1]];
}

How to simplify an array with PHP

Seems like a pretty basic question, but how can I simplify an array such as:
Array
(
[0] => Array
(
[blue_dog_1] => 2
)
[1] => Array
(
[red_dog_1] => 4
)
[2] => Array
(
[red_dog_2] => 6
)
)
To be like:
Array
(
[blue_dog_1] => 2
[red_dog_1] => 4
[red_dog_2] => 6
)
Thanks in advance.
Try this way to make it single dimension from multi dimension using array_merge
$singleD = array_reduce($multiD, 'array_merge', array());
OR
$singleD = call_user_func_array('array_merge', $multiD);
Try this,
foreach($array as $sub_val)
{
foreach($sub_val as $key=>$val)
{
$new_array[$key] = $val;
}
}
print_r($new_array);
To accomplish this you can simply use array union operator.
$oldData = array(
0 => array('blue_dog_1'=>2),
1 => array('red_dog_1'=>4),
2 => array('red_dog_2'=>6)
);
$newData = array();
foreach ($oldData as $arrayData) {
$newData += $arrayData;
}
print_r($newData);

How to build custom array in multi level foreach?

Here is the raw data
Array
(
[name] => me
[tickets] => Array
(
[1] => Array
(
[equipment] => Array
(
[1] => Array
(
[name] => DVR
[received] => 10
)
[2] => Array
(
[name] => DCT
[received] => 3
)
)
)
[2] => Array
(
[equipment] => Array
(
[1] => Array
(
[name] => DVR
[received] => 4
)
[2] => Array
(
[name] => DCT
[received] => 6
)
)
)
)
)
Users have multiple tickets, but each ticket has the same item with different 'received' amounts. I would like to sum the received amount into one variable/array.
Here is a demo of how I would like to get it to work like
Array
(
[name] => me
[equipment] => Array
(
[DVR] => 14
[DCT] => 9
)
)
Here is my most recent failed attempt at building my own array from a multidimensional array.
foreach($data as $user){
$sum = [];
$sum['name'] = $user->name;
$sum['equipment'] = [];
foreach($user->tickets as $ticket){
foreach($ticket->equipments as $eqpt){
$sum['equipment'][$eqpt['name']] += $eqpt['pivot']['received'];
}
}
print_r($sum);
}
Please try the following code. There's only a single user in your $data, though, so you need to do $data = [$data]; first.
foreach ($data as $user) {
$sum = [];
$sum['name'] = $user['name'];
$sum['equipment'] = [];
foreach($user['tickets'] as $ticket){
foreach($ticket['equipment'] as $eqpt){
$sum['equipment'][$eqpt['name']] += $eqpt['received'];
}
}
print_r($sum);
}
PHP arrays are accessed with square bracket syntax
There's probably a typo in $ticket->equipments.
Try with this:
$array = $data; //$data is your array
$sum = array('name' => $array['name'], 'equipment' => array());
foreach($array['tickets'] as $row) {
for($i = 0; $i < count($row); $i++) {
foreach($row['equipment'] as $infos) {
$sum['equipment'][$infos['name']] += $infos['received'];
//print_r($infos);
}
}
}
print_r($sum);
well, after much googling and trial and error this appears to work
$sum = [];
// $data is a collection returned by Laravel
// I am converting it to an array
foreach($data->toArray() as $user){
$items = [];
foreach($user['tickets'] as $ticket){
foreach($ticket['equipments'] as $eqpt){
$name = $eqpt['name'];
if (! isset($items[$name]))
{
$items[$name] = $eqpt['received'];
} else {
$items[$name] += $eqpt['received'];
}
}
}
$sum[] = [
'name' => $user['name'],
'equipment' => $items
];
}
#tsnorri #Adrian Cid Almaguer

Formatting an Array in PHP

I'm pulling an array from the database and it looks like so:
Array
(
[0] => Array
(
[tracker_id] => 28
[tracking_numbers] => hdkshwuy47937892hd
)
[1] => Array
(
[tracker_id] => 28
[tracking_numbers] => 797825464411
)
)
I need to reformat it to look like this:
Array
(
[0] => Array
(
[tracker_id] => 28
[tracking_numbers] => Array
(
[0] => hdkshwuy47937892hd
[1] => 797825464411
)
)
)
I can't seem find the right search in the array or keys to create an array of numbers for the single tracker id.
Use array_column() for < php V5.5
<?php
$a=array
( array
('tracker_id' => 28,
'tracking_numbers'=> "hdkshwuy47937892hd"
),
array('tracker_id' => 28,
'tracking_numbers' => "797825464411",
) );
$a[0]['tracking_numbers']=array_column($a,"tracking_numbers");
unset($a[1]);
print_r($a);
Demo
try this
$arr_output = array();
foreach($arr_input as $arr)
{
$tracker_id = $arr['tracker_id'];
$tracking_numbers = $arr['tracking_numbers'];
$arr_output[$traker_id][] = $tracking_numbers;
}
print_r($arr_output);
UPDATE 2:
$arr_output = array();
$arr_output1 = array();
foreach($arr_input as $arr)
{
$tracker_id = $arr['tracker_id'];
$tracking_numbers = $arr['tracking_numbers'];
$arr_output[$traker_id][] = $tracking_numbers;
}
$i=0;
foreach($arr_output as $key=>$value)
{
$arr_output1[$i]['tracker_id']=$key
$arr_output1[$i]['tracking_numbers']=$value
$i+=1;
}
print_r($arr_output1);

Sum multidimensional associative array values while preserving key names

There are many nice Q&A on Stackoverflow on how to take a multidimensional associative array and sum values in it. Unfortunately, I can't find one where the key names aren't lost.
For example:
$arr=array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
I want the resulting array to look like this:
$result=array(
array('id'=>'1', 'amount'=>'10'),
array('id'=>'2', 'amount'=>'4')
);
Unfortunately the only thing I can figure out how to do is this:
$result = array();
foreach($arr as $amount){
if(!array_key_exists($amount['id'], $arr))
$result[$amount['id']] =0;
$result[$amount['id']] += $amount['amount'];
}
Which when echo'd as follows produces (notice the lack of the keys' words "id" and "amount"):
foreach($result as $id => $amount){
echo $id."==>".$amount."\n";
}
1==>10
2==>4
This is just to show that you already had the data you originally needed, though, the answer you accepted is a better way to deal with it.
You have the following to start with right?
$arr = array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
Output
Array
(
[0] => Array
(
[id] => 1
[amount] => 5
)
[1] => Array
(
[id] => 1
[amount] => 5
)
[2] => Array
(
[id] => 2
[amount] => 1
)
[3] => Array
(
[id] => 2
[amount] => 3
)
)
Then you run it through the following algorithm:
$summedArr = array();
foreach ($arr as $amount) {
$summedArr['amount'][$amount['id']] += $amount['amount'];
$summedArr['id'][$amount['id']] = $amount['id'];
}
Now, disregarding the Notice warnings that are produced since you are referencing indexes that don't yet exist, this outputs the following:
Output
Array
(
[amount] => Array
(
[1] => 10
[2] => 4
)
[id] => Array
(
[1] => 1
[2] => 2
)
)
Do you see the keys, yet? Because I do.
Now iterate over the array:
foreach ($summedArr as $key => $value) {
echo $k . "==>" . $v . "\n";
}
Output
amount==>Array
id==>Array
That's not what you want, though. You want:
foreach ($summedArr as $key => $arr) {
foreach ($arr as $v) {
echo $key . "==>" . $v;
}
}
Why not use that method, and then reconstruct the array you want at the end?
$results = array();
foreach ($arr as $id=>$amount) {
$results[] = array('id' => $id, 'amount' => $amount);
}
Any other way of doing this would be more computationally expensive.

Categories