How to merge two different array PHP - php

I would need to combine two different fields.
In the first field I generate days of the month. I want to list all days of the month.
I would like to add a second field to them, where there are items for each day. But, for example, there are no items on weekends or on other days. Ie. that field two will always have fewer items.
The second field is tightened from the DB.
I would need to do a JOIN like in MySQL for the first field.
It occurred to me that in MySQL it would be possible to make a temporary table with a given month and link it here, but I don't think it's right.
$arrayDate = [0 => '20210401',1 => '20210402',2 => '20210403',3 => '20210404',4 => '20210405',5 => '20210406',6 => '20210407',7 => '20210408',8 => '20210409',9 => '20210410',10 => '20210411',11 => '20210412',12 => '20210413',13 => '20210414',14 => '20210415',15 => '20210416',16 => '20210417',17 => '20210418',18 => '20210419',19 => '20210420',20 => '20210421',21 => '20210422',22 => '20210423',23 => '20210424',24 => '20210425',25 => '20210426',26 => '20210427',27 => '20210428',28 => '20210429',29 => '20210430'];
$arrayItem[35] = ['id' => 35, 'date' => '20210401', 'item' => 'aaaa'];
$arrayItem[36] = ['id' => 36, 'date' => '20210402', 'item' => 'bbbb'];
$arrayItem[37] = ['id' => 36, 'date' => '20210430', 'item' => 'cccc'];
// i need output
20210401 - aaaa
20210402 - bbbb
20210403 - empty
20210404 - empty
...
20210430 - cccc
EDIT: I use nested loops, but I still can't get the right output
foreach ($arrayDate as $date) {
foreach ($arrayItem as $item) {
if ($date == $item['date']) {
bdump($item['date']);
} else {
bdump($date);
}
}
}
bdump($item['date']) = '20210401', '20210402', '20210430'
bdump($date) = '20210401', '20210401', '20210402', '20210402', '20210403', '20210403', '20210403', '20210404', '20210404', '20210404', '20210405', '20210405', '20210405' ....

With array_column you create a array from $arrayItem with date as key.
$dateItem is an array like
array (
20210401 => "aaaa",
20210402 => "bbbb",
20210430 => "cccc",
)
The output you can do with a simple foreach.
$dateItem = array_column($arrayItem,'item','date');
foreach($arrayDate as $date){
echo $date.' '.($dateItem[$date] ?? 'empty')."<br>\n";
}
Note:
With
array_column($arrayItem,null,'date')
you get a two-dimensional array with a date as a key that can be used.
array (
20210401 =>
array (
'id' => 35,
'date' => "20210401",
'item' => "aaaa",
),
20210402 =>
array (
'id' => 36,
'date' => "20210402",
'item' => "bbbb",
),
20210430 =>
array (
'id' => 36,
'date' => "20210430",
'item' => "cccc",
),
)

Related

MongoDb aggregate error "each element of the 'pipeline' array must be an object"

Here is my aggregation code for mongodb collection :
$mongo_db_name = "db_".$tenant_id;
$con = new MongoClient($this->config->item('mongo_instance'));
$db = $con->$mongo_db_name;
$collection = $db->$module;
$options = array('cursor' => array("batchSize" => 4 ));
$pipeline=array(
array('$match'=>array('deleted'=>'0')),
array('$group'=>array('_id' => array('id'=>'$id', 'accountnm' => '$account_name', 'legal___corporate_name_cstm' => '$legal___corporate_name_cstm', 'funded_by_cstm' => '$funded_by_cstm', 'approval_amount_cstm' => '$approval_amount_cstm', 'payback_amount_cstm' => '$payback_amount_cstm', 'factor_rate_cstm' => '$factor_rate_cstm', 'daily_ach_amount__1_cstm' => '$daily_ach_amount__1_cstm', 'total_commission_owed_cstm' => '$total_commission_owed_cstm', 'total_commission_paid_cstm' => '$total_commission_paid_cstm', 'upfront_amount_due_cstm' => '$upfront_amount_due_cstm', 'upfront_amount_due_date_cstm' => '$upfront_amount_due_date_cstm', 'date_modified' => '$date_modified'))),
);
$data = $collection->aggregate($pipeline,$options);
var_dump($data);
I am getting this error with the above code
array (size=4) 'ok' => float 0 'errmsg' => string 'Each element of
the 'pipeline' array must be an object' (length=54) 'code' => int 14
'codeName' => string 'TypeMismatch' (length=12)
If I try to encode the pipeline using json_encode the result is 'null'.
If I use find(array('deleted'=>'0')); it returns all documents as expected.
Can anyone help me about where I am going wrong or whatmust I do to resolve this ?
aggregation pipeline takes objects in array so your pipeline should be like
[
{$match:{}};
{$group:{}};
{$somepipelinestageOperator:{}}
]
but if you have pipeline with array as tages and not object you will get above error(each element of pipeline must be an array..).
[
[$match:{}],
[$group:{}],
[$somepipelinestageOperator:{}]
]
in your code there are array for match and group so its failing.
$pipeline=array(
array('$match'=>array('deleted'=>'0')),
array('$group'=>array('_id' => array('id'=>'$id', 'accountnm' => '$account_name', 'legal___corporate_name_cstm' => '$legal___corporate_name_cstm', 'funded_by_cstm' => '$funded_by_cstm', 'approval_amount_cstm' => '$approval_amount_cstm', 'payback_amount_cstm' => '$payback_amount_cstm', 'factor_rate_cstm' => '$factor_rate_cstm', 'daily_ach_amount__1_cstm' => '$daily_ach_amount__1_cstm', 'total_commission_owed_cstm' => '$total_commission_owed_cstm', 'total_commission_paid_cstm' => '$total_commission_paid_cstm', 'upfront_amount_due_cstm' => '$upfront_amount_due_cstm', 'upfront_amount_due_date_cstm' => '$upfront_amount_due_date_cstm', 'date_modified' => '$date_modified'))),
);
you can print your pipeline and see that your pipeline stages are having array and not object.

Get the intersect of tables

I have a question. So I have this array :
$a_list_id = array(
0 => 1234
1 => 739
3 => 538
);
And this array :
$a_users = array(
0 => array(
id => 15627,
name => test
),
1 => array(
id => 1234,
name => test1
),
2 => array(
id => 739,
name => test2
)
)
The result should be :
$a_response = array(
0 => array(
id => 1234,
name => test1
)
)
Because the id 1234 is in both arrays.
I try with array_intersect but not work. Can you help me please ?
Just use loops :
$a_response = array();
foreach ($a_users as $array) {
if (in_array($array['id'], $a_list_id)) {
$a_response []= $a_users;
}
}
array_intersect will only produce useful results if the values of both arrays can be cast to the same type. You've got an array of integers and another array of arrays, they can never* match so intersect will always be empty
If you want an intersection between the arrays then you have two options:
Index the arrays so their keys are the values you want to intersect and use array_intersect_key
Implement your own array comparison logic with array_uintersect and a callback function that knows the structure of the arrays being compared
example of the former:
$a_list_id = array(
1234 => 1234
739 => 739
538 => 538
);
$a_users = array(
15627 => array(
id => 15627,
name => test
),
1234 => array(
id => 1234,
name => test1
),
739 => array(
id => 739,
name => test2
)
)
var_dump (array_intersect_key ($a_users, $a_list_id));
Example of the latter:
var_dump (array_uintersect ($a_users, $a_list_id, function ($user, $id) {
return $user ["id"] - $id; // Result should be 0 if they match, as per documentation
}))
*They can be considered the same in the case where one value is integer 0 and the other is an empty array, but that's not very useful
Try the below code using array_search() function:
$a_list_id = array(1234, 538,739);
$a_users = array(
array(
'id'=> 15627,
'name' => 'test'
),
array(
'id' => 1234,
'name' => 'test1'
),
array(
'id' => 739,
'name' => 'test2'
)
);
foreach($a_users as $a_user){
if (in_array($a_user['id'], $a_list_id)) {
$a_response[array_search($a_user['id'], $a_list_id)] = $a_user;
}
}
print_r($a_response);
Have you tried using array_intersect_uassoc? http://php.net/manual/en/function.array-intersect-uassoc.php
function compare_ids($a, $b)
{
return $a - $b['id'];
}
print_r(array_intersect_uassoc($a_list_id, $a_users, "compare_ids"));

Transpose an array of arrays [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 6 months ago.
Hah, I had no idea how else to phrase that. I'm trying to reformat a set of three arrays generated by form field inputs, into something that better matches my models, so I can save the values to the db.
Not sure if the solution should be some array manipulation or that I should change the "name" attribute in my form fields.
currently I have an array of my input data:
array(
'image_id' =>
array
0 => '454' (length=3),
1 => '455' (length=3),
2 => '456' (length=3)
'title' =>
array
0 => 'title1' (length=6),
1 => 'title2' (length=0),
2 => '' (length=6)
'caption' =>
array
0 => 'caption1' (length=8),
1 => '' (length=8),
2 => 'caption3' (length=8)
);
and would like to change it to something like, so I can iterate over and save each array of values to the corresponding resource in my db.
array(
0 =>
array
'image_id' => '454',
'title' => 'title1',
'caption' => 'caption1'
1 =>
array
'image_id' => '455',
'title' => 'title2',
'caption' => ''
2 =>
array
'image_id' => '456',
'title' => '',
'caption' => 'caption3'
);
This would iterate through the array with 2 foreach loops. They would use each other's key to construct the new array, so it would work in any case:
$data = array(
'image_id' => array(454, 455, 456),
'title' => array('title1', 'title2', ''),
'caption' => array('caption1', '', 'caption3')
);
$result = array();
foreach($data as $key => $value) {
foreach ($value as $k => $v) {
$result[$k][$key] = $v;
}
}
This'll do it:
$array = call_user_func_array('array_map', array_merge(
[function () use ($array) { return array_combine(array_keys($array), func_get_args()); }],
$array
));
Assuming though that this data is originally coming from an HTML form, you can fix the data right there already:
<input name="data[0][image_id]">
<input name="data[0][title]">
<input name="data[0][caption]">
<input name="data[1][image_id]">
<input name="data[1][title]">
<input name="data[1][caption]">
Then it will get to your server in the correct format already.

Displaying one string from a list of multiple strings

I'm trying to grab data from this array, but when I do var_dump($ArrayedLevels['Attack']); it returns NULL, I know for a fact that it was able to grab the data from the SQL database, I think it has something to do with my array. Any help would be greatly appreciated.
include("highscoresconfig.php");
$GrabXP = $database2->prepare("SELECT * FROM `skills` WHERE `playerName` = ?");
$GrabXP->execute(array($playerName));
$MainResult = $GrabXP->fetchAll();
$ArrayedLevels = $array = [
"Attack" => $MainResult['Attacklvl'],
"Defence" => $MainResult['Defencelvl'],
"Strength" => $MainResult['Strengthlvl'],
"Hitpoints" => $MainResult['Hitpointslvl'],
"Ranged" => $MainResult['Rangelvl'],
"Prayer" => $MainResult['Prayerlvl'],
"Magic" => $MainResult['Magiclvl'],
"Cooking" => $MainResult['Cookinglvl'],
"Woodcutting" => $MainResult['Woodcuttinglvl'],
"Fletching" => $MainResult['Fletchinglvl'],
"Fishing" => $MainResult['Fishinglvl'],
"Firemaking" => $MainResult['Firemakinglvl'],
"Crafting" => $MainResult['Craftinglvl'],
"Smithing" => $MainResult['Smithinglvl'],
"Mining" => $MainResult['Mininglvl'],
"Herblore" => $MainResult['Herblorelvl'],
"Agility" => $MainResult['Agilitylvl'],
"Thieving" => $MainResult['Thievinglvl'],
"Slayer" => $MainResult['Slayerlvl'],
"Farming" => $MainResult['Farminglvl'],
"Runecrafting" => $MainResult['Runecraftlvl'],
"Hunter" => $MainResult['Hunterlvl'],
"Construction" => $MainResult['Constructionlvl'],
"Summoning" => $MainResult['Summoninglvl'],
"Dungeoneering" => $MainResult['Dungeoneeringlvl'],
];
var_dump($ArrayedLevels["Attack"]);
Problem might be because the fetchAll() returns all the rows of your query.
if($GrabXP->execute(array($playerName))){
//Success
$MainResult = $GrabXP->fetchAll();
/*
This will give you all the rows. Use a foreach loop to iterate through all the rows.
If you want only the first row, add this-
*/
$MainResult = $MainResult[0];
//The rest of your code.
$ArrayedLevels = $array = Array(
"Attack" => $MainResult['Attacklvl'],
...
);
var_dump($ArrayedLevels["Attack"]);
}
else{
//Failure
}
The brackets don't work in PHP when creating a new array, use array() to create one.
Actually: as of PHP 5.4 they do work, see here: http://nl3.php.net/manual/en/language.types.array.php
Try var_dump($MainResult);
if all good, try create your array like this:
$ArrayedLevels = array(
"Attack" => $MainResult['Attacklvl'],
"Defence" => $MainResult['Defencelvl'],
"Strength" => $MainResult['Strengthlvl'],
"Hitpoints" => $MainResult['Hitpointslvl'],
"Ranged" => $MainResult['Rangelvl'],
"Prayer" => $MainResult['Prayerlvl'],
"Magic" => $MainResult['Magiclvl'],
"Cooking" => $MainResult['Cookinglvl'],
"Woodcutting" => $MainResult['Woodcuttinglvl'],
"Fletching" => $MainResult['Fletchinglvl'],
"Fishing" => $MainResult['Fishinglvl'],
"Firemaking" => $MainResult['Firemakinglvl'],
"Crafting" => $MainResult['Craftinglvl'],
"Smithing" => $MainResult['Smithinglvl'],
"Mining" => $MainResult['Mininglvl'],
"Herblore" => $MainResult['Herblorelvl'],
"Agility" => $MainResult['Agilitylvl'],
"Thieving" => $MainResult['Thievinglvl'],
"Slayer" => $MainResult['Slayerlvl'],
"Farming" => $MainResult['Farminglvl'],
"Runecrafting" => $MainResult['Runecraftlvl'],
"Hunter" => $MainResult['Hunterlvl'],
"Construction" => $MainResult['Constructionlvl'],
"Summoning" => $MainResult['Summoninglvl'],
"Dungeoneering" => $MainResult['Dungeoneeringlvl'],
);
first of all try to print the structure of the variable $MainResult:
var_dump($MainResult);
FetchAll return an array with all restuls like
resutl = [
[0] => ['first row'],
[1] => ['sec. row']
]
you will See The variable $MainResult looks like:
MailResult => [
[0] => ['Attacklvl' => 'foo'],
[1] => ['Defencelvl' => 'bar']
]

Array in a Array SOAP V2 (WS-I Compliance Mode)

$result = $proxy->salesOrderInvoiceCreate((object)array('sessionId' => $sessionId->result, 'itemsQty' => array('order_item_id' => 15, 'qty' => '1')));
$mainarray[];
$itemarray[];
I need multiple of this
array('order_item_id' => 15, 'qty' => '1')
Which means i need a array in a array.
foreach(statement){
array_push($itemarray, "order_item_id", echo $item->product_id;);
array_push($itemarray, "qty", echo $item->qty);
array_push($mainarray, $itemarray);
}
enter code here
Request Example SOAP V2 (WS-I Compliance Mode)
http://www.magentocommerce.com/api/soap/sales/salesOrderInvoice/sales_order_invoice.create.html
In fact i'm also not sure what do i replace the current
array('order_item_id' => 15, 'qty' => '1')
with
array($mainarray) ??
That is not the correct way of using array_push your current $itemarray output will look something like
Array
(
[0] => 'order_item_id'
[1] => '200'
[2] => 'qty'
[3] => '2'
)
I would go back to basics and use something like to generate your multi dimensional array:
$itemarray[] = array("order_item_id" => $item->product_id, "qty" => $item->qty);
array_push($mainarray, $itemarray);
Edit:
Ok I reread your questions, ignore $mainArray.
$result = $proxy->salesOrderInvoiceCreate((object)array('sessionId' => $sessionId->result, 'itemsQty' => $itemarray));
That should work as with the other examples qty/itemsQty show it accepting multikey arrays.

Categories