mongodb php cant push to end of array - php

Hello i tried (permutated actually) every single way of inserting to in array in mongodb, nothing is working how im expecting it.
this is the structure of the document that i want to push into
["test123"]=>
array(6) {
["_id"]=>
string(7) "test123"
["products"]=>
array(1) {
[0]=>
array(9) {
["task_description"]=>
string(0) ""
["priority"]=>
string(4) "high"
["done"]=>
string(4) "true"
["extended_price"]=>
string(1) "0"
["unit_price"]=>
string(1) "0"
["qty"]=>
string(1) "0"
["description"]=>
string(18) "sample description"
["item"]=>
string(7) "Service"
["date_done"]=>
string(10) "2013-06-03"
}
}
["total"]=>
string(1) "0"
["tax"]=>
string(1) "0"
["discount"]=>
string(1) "0"
["currency"]=>
string(3) "EUR"
}
}
I want to push another array in the format of products[0] to products.
Here is the code that i try to do it with.
$collection->update(
array("_id" => $id),
// THIS REPLACES [0] ELEMENT IN ARRAY 'PRODUCTS' BUT I DONT WANT THAT
// array('$push' => array("products"=>array(0=>$data)))
// THIS IS NOT WORKING AT ALL
array('$push' => array('products' => $data))
);

What is the exact error you're seeing? Given the example document you shared, I can't reproduce either of your issues (products[0] being overwritten or the vague "this isn't working at all" comment).
I achieved the desired outcome with the following, which happens to match your code above:
$m = new MongoClient();
$c = $m->test->foo;
$c->drop();
// Create a document with a "p" array containing one embedded object
$c->insert(['p' => [['a' => 1, 'b' => 1]]]);
// This would add a second element to the "p" array, which would be
// a single-element array containing our embedded object
$c->update([], ['$push' => ['p' => [0 => ['a' => 2, 'b' => 2]]]]);
// This appends an embedded object to the "p" array
$c->update([], ['$push' => ['p' => ['a' => 2, 'b' => 2]]]);
// Debugging
var_export(iterator_to_array($c->find()));

Related

Array into array using array_push key issue

I'm getting confused about how to insert array into array and give it a key name. Not number!.
I have the main array, which contains info about customer. the sub array should be called ["verlauf"].
The ["verlauf"] array conatins multiple arrays ( as same as db row count ). the main idea is that the sub array should be having the key name ["verlauf"]. in my code im getting the [0] as key.
Current array output:
array(19) {
["id"]=> string(1) "1"
["name"]=> string(11) "qwert zuiop"
["email"]=> string(23) "xy#gmail.com"
["phn_num"]=> string(12) "123456789"
[0]=> array(1) {
[0]=> array(4) {
["datum"]=> string(10) "30.07.2020"
["uhr_zeit"]=> string(5) "22:25"
["status"]=> string(1) "0"
["info"]=> string(34) "some info"
}
[1]=> array(4) {
["datum"]=> string(10) "30.07.2020"
["uhr_zeit"]=> string(5) "23:25"
["status"]=> string(1) "1"
["info"]=> string(34) "some info"
}
}
}
what i want is that the [0] on line 6 in the above example to be ["verlauf"]
My PHP:
while ($row = mysqli_fetch_array($result)) {
$verlaufArray[] = array(
"datum" => $row['datum'],
"uhr_zeit" => $row['uhr_zeit'],
"status" => $row['status'],
"info" => $row['info']);
}
array_push($returnArray, $verlaufArray);
Please note that $returnArray is the "main array".
You can simply do that by using associate array-
Your PHP code -
while ($row = mysqli_fetch_array($result)) {
$verlaufArray[] = array(
"datum" => $row['datum'],
"uhr_zeit" => $row['uhr_zeit'],
"status" => $row['status'],
"info" => $row['info']);
}
$returnArray['verlauf'] = $verlaufArray;
There's no need to complicate things so much. It looks like you need just one line of code.
$returnArray['verlauf'] = $result->fetch_all(MYSQLI_ASSOC);
There's no need for the while loop if the structure remains the same. fetch_all(MYSQLI_ASSOC) will give you an array containing associative results from your query.

PHP Array key exist

I'm working with an API and now i want to check if an array key exists then do something.
With an array i gather data like this:
$pers_payload = array(
'gender' => 'Unknown', //or Male / Female
'first_name' => $_POST['billing_first_name'],
'family_name' => $_POST ['billing_last_name'],
'email' => $_POST['billing_email'],
'linked_as_contact_to_organization' => array(
array(
'organization_id' => $organization_id, // add the person as a contact to the newly created organization
'work_email' => $_POST['billing_email'],
'work_phone' => $_POST['billing_phone']
)
),
'visiting_address' => array(
'country_code' => 'NL'
), // can be extented with other address data
'postal_address' => array(
'country_code' => $_POST['billing_country']
) // can be extented with other address data
);
Then i use a get request like this:
$tet = $SimplicateApi->makeApiCall('GET','/crm/person?q[first_name]=Kevin');
And then i check if the array exists inside the results of the get request like this:
if(array_key_exists('first_name', $tet)) {
// do Nothing
}else{
// make API call
$person = $SimplicateApi->makeApiCall('POST','/crm/person',json_encode($pers_payload));
}
Im sure the get request is working, because i did a var_dump($tet); and i got this result:
array(3) { ["data"]=> array(6) { [0]=> array(18) { ["id"]=> string(39) "person:71cf33fb785433ab66550e5701120079
Well thats part of what i got, i cant post all of it. because it contains sensitive information.
For some reason even if the array_key exists this code still runs:
$person = $SimplicateApi->makeApiCall('POST','/crm/person',json_encode($pers_payload));
--
array(3) { ["value"]=> bool(false) ["id"]=> string(41) "interest:7d3458131ea89afbe1bb3149bee8b668" ["name"]=> string(3) "Web" } } } } ["gender"]=> string(7) "Unknown" ["first_name"]=> string(5) "Kevin" ["family_name"]=> string(7) "A" ["full_name"]=> string(13) "Kevin A" ["email"]=> string(24) "ma#edd-marketingsuppxort.nl" ["phone"]=> string(8) "06269684" } [5]=> array(11) { ["id"]=> string(39) "person:51045f230a9cc39136aaf3a22a069eb0" ["interests"]=> array(1) { [0]=>
What are the first array keys of $tet?
We can see the first one is data, but what about the others one?
if(array_key_exists('first_name', $tet['data'])) {
//code...
}
edit: as #lma says array_key_exists can not dig into child, and even the edited structure you gave us look weird, some trailing } in the middle of the array.

Strange array layout while using array_push with multidimensional arrays

Sorry if there's too much code in this question. Arrays takes up a lot of space and I'm trying to explain this as thorough as I can. I'm trying to save all of the addresses user entered into one multidimensional array, so I could easily loop trough them after. Final result of what I'm trying to achieve in theory looks like this:
array(3) {[0]=>
array(4) {
["street_address"]=>
string(1) "a"
["city_name"]=>
string(1) "a"
["zip"]=>
string(1) "a"
["country_select"]=>
string(2) "LT"
}
[1]=>
array(4) {
["street_address"]=>
string(1) "b"
["city_name"]=>
string(1) "b"
["zip"]=>
string(1) "b"
["country_select"]=>
string(2) "LT"
}
[2]=>
array(4) {
["street_address"]=>
string(1) "c"
["city_name"]=>
string(1) "c"
["zip"]=>
string(1) "c"
["country_select"]=>
string(2) "LT"
}}
I could easily replicate this with simple code
$adresai = array();
$adresas =array(
'street_address' => 'a',
'city_name' => 'a',
'zip' => 'a',
'country_select' => 'a');
array_push($adresai, $adresas);
array_push($adresai, $adresas);
array_push($adresai, $adresas);
but when I'm trying to apply this logic in wordpress I get really strange layout, basically a mess.
array(1) {
[0]=>
array(2) {
[0]=>
array(2) {
[0]=>
array(4) {
["street_address"]=>
string(1) "a"
["city_name"]=>
string(1) "a"
["zip"]=>
string(1) "a"
["country_select"]=>
string(2) "LT"
}
[1]=>
array(4) {
["street_address"]=>
string(1) "b"
["city_name"]=>
string(1) "b"
["zip"]=>
string(1) "b"
["country_select"]=>
string(2) "LT"
}
}
[1]=>
array(4) {
["street_address"]=>
string(1) "c"
["city_name"]=>
string(1) "c"
["zip"]=>
string(1) "c"
["country_select"]=>
string(2) "LT"
}}}
My snippet for saving user entered address and merging with previous ones:
$adresai =get_user_meta(get_current_user_id(), 'stakliu_adresai');
$adresas =array(
'street_address' => $_POST['snr_gatve'],
'city_name' => $_POST['snr_miestas'],
'zip' => $_POST['snr_pastokodas'],
'country_select' => $_POST['snr_salis']);
if ($adresai == array()){
$adresai = $adresas;
}
else{
array_push($adresai, $adresas);
}
update_user_meta(get_current_user_id(),'stakliu_adresai', $adresai );
What am I doing wrong?
I would say part of your issue lies in:
if ($adresai == array()) {
$adresai = $adresas;
}else ...
You are planning on storing multiple addresses. An array of arrays. If the value does not exist, you are simply setting it to an array, as opposed to adding it to an array. Since you are expecting an empty array if nothing is set, you can simply push regardless, like so:
$adresai =get_user_meta(get_current_user_id(), 'stakliu_adresai');
$adresas = array(
'street_address' => $_POST['snr_gatve'],
'city_name' => $_POST['snr_miestas'],
'zip' => $_POST['snr_pastokodas'],
'country_select' => $_POST['snr_salis']
);
//if the array is empty, this address will become the first value
//if the array is not empty, this address will be added to the array
array_push($adresai, $adresas);
//save
update_user_meta(get_current_user_id(),'stakliu_adresai', $adresai );
So as naththedeveloper advised, I added parameter $single = true, which returns meta value without additional array "wrapping". But when meta is not set yet, function returns an empty string. To avoid errors I still had to use conditional statement. I finally got it working with this:
$adresai = get_user_meta(get_current_user_id(), 'stakliu_adresai', true);
$adresas = array(
'street_address' => $_POST['snr_gatve'],
'city_name' => $_POST['snr_miestas'],
'zip' => $_POST['snr_pastokodas'],
'country_select' => $_POST['snr_salis']);
// checking if value was not set earlier
if ($adresai == ''){
$adresai = array();
}
array_push($adresai, $adresas);
update_user_meta(get_current_user_id(),'stakliu_adresai', $adresai );

compare array data and get an merged output in php

I have an array like this. I want remove elements with duplicate id and get sum of the count
array(3) {
[0]=>
array(3) {
["Id"]=>
string(1) "1"
["Name"]=>
string(1) "a"
["Count"]=>
string(1) "2"
}
[1]=>
array(3) {
["Id"]=>
string(1) "2"
["Name"]=>
string(1) "b"
["Count"]=>
string(1) "1"
}[2]=>
array(3) {
["Id"]=>
string(1) "1"
["Name"]=>
string(1) "a"
["Count"]=>
string(1) "1"
}
}
and I need to remove elements with duplicate id and get sum of the count as shown below
array(2) {
[0]=>
array(3) {
["Id"]=>
string(1) "1"
["Name"]=>
string(1) "a"
["Count"]=>
string(1) "3"
}[1]=>
array(3) {
["Id"]=>
string(1) "2"
["Name"]=>
string(1) "b"
["Count"]=>
string(1) "1"
}
}
I have gone through many examples.. but couldn't find an answer..
Unfortunately there is no way around looping. Assuming that Name is the same for the same Id or that you don't care about the value of Name:
foreach($array as $value) {
if(!isset($result[$value['Id']])) {
$result[$value['Id']] = $value;
} else {
$result[$value['Id']]['Count'] += $value['Count'];
}
}
// re-index if needed
$result = array_values($result);
Loop the array and build result array using Id as key
If the key Id doesn't exist create it
If it does exist add Count to the current Count
just create a new array, loop through current, create if doesnt exist, and insert values (sum) into new one
what are you doing with duplicates names?
example below. hope it will help.
<?php
$tArr = array(
array(
"Id" => "1",
"Name" => "a",
"Count" => "2",
),
array(
"Id" => "2",
"Name" => "b",
"Count" => "1",
),
array(
"Id" => "1",
"Name" => "a",
"Count" => "1",
)
);
$rez = array();
foreach ($tArr as $key => $element) {
if (empty($rez[$element["Id"]])) {
$rez[$element["Id"]] = $element;
} else {
$rez[$element["Id"]]["Count"] += $element["Count"];
}
}
var_dump($rez);
/** array (size=2)
1 =>
array (size=3)
'Id' => string '1' (length=1)
'Name' => string 'a' (length=1)
'Count' => int 3
2 =>
array (size=3)
'Id' => string '2' (length=1)
'Name' => string 'b' (length=1)
'Count' => string '1' (length=1)**/
Try this
$result = array_diff_assoc($arr, array_unique($arr));
print_r($result);

laravel 4 form submit with multiple input

this is the var_dump($_POST) :
array(18) { ["_token"]=> string(40) "Qg0krYddkI2cnPQBy5T3yGJdQqRBbb9q173MXzoa" ["from_name"]=> string(2) "4r" ["from_address"]=> string(1) "4" ["invoice_id"]=> string(1) "4" ["invoice_date"]=> string(0) "" ["due_date"]=> string(0) "" ["to_name"]=> string(1) "4" ["to_address"]=> string(1) "4" ["item"]=> array(1) { [0]=> string(5) "Hours" } ["desc"]=> array(1) { [0]=> string(2) "44" } ["​unitAmt"]=> array(1) { [0]=> string(1) "4" } ["​qty"]=> array(1) { [0]=> string(1) "4" } ["​amount"]=> array(1) { [0]=> string(2) "16" } ["invoiceNotes"]=> string(2) "44" ["subTotal"]=> string(2) "16" ["total"]=> string(2) "16" ["amtPaid"]=> string(1) "0" ["balDue"]=> string(2) "16" }
As you can see the variable unitAmt is being posted, but I am getting this error when I use it :
ErrorException
Undefined index: unitAmt
open: /var/www/lk/htdocs/app/routes.php
//var_dump($rows);
//var_dump($description);
for($i=0; $i<count($rows);$i++){
DB::table('item_description')->insert(
array('invoice_id' => $returnID, 'item' => $rows[$i], 'description' => $description[$i],
'unit_price' => $_POST['unitAmt'][$i], 'quantity' => $_POST['​qty'][$i], 'amount'=>$_POST['​amount'][$i]));
}
This works fine for qty and amount which are posted similarly. Same thing is happening at other places also on dumping a variable I can see data is there but when I use it shows undefined index.
Edit :
THis is my code in route.php
var_dump($_POST);
$rows = $_POST['item'];
$description = $_POST['desc'];
for($i=0; $i<count($rows);$i++){
DB::table('item_description')->insert(
array('invoice_id' => $returnID, 'item' => $rows[$i], 'description' => $description[$i],
'unit_price' => $_POST['unitAmt'][$i], 'quantity' => $_POST['​qty'][$i], 'amount'=>$_POST['​amount'][$i]));
}
Why are you using Laravel to use standard PHP functions? That kind of insertion code shouldn't be in the routes.php file, it should be in a controller or a closure. You should probably using an Eloquent model to create items. Furthermore, you can use the Input class to retrieve data that is provided by GET or POST parameters.
I recommend you to use Eloquent model to insert an ITEM data like this way and also loop thru for all the items in your result set:-
Use input class to get POST and GET variables in laravel way
Input::get('invoice_id')
method get() - returns the POST and GET vars
method e() - Convert HTML characters to entities and defined in laravel/helper.php
Use Eloquent to add new row in db in laravel way like:-
item_description::create($arr);
A simple example that is adding an item to item_description table in a cleaner Laravel way:-
$arr = array(
'invoice_id' => e(Input::get('invoice_id')),
'item' => e(Input::get('item')),
'description' => e(Input::get('desc')),
'unit_price' => e(Input::get('unitAmt')),
'quantity' => e(Input::get('qty')),
'amount' => e(Input::get('amount')),
);
// Insert Data in table
$item_description= item_description::create($arr);

Categories