i am new in PHP coding, i wanna add some variable value in a multi array dynamically, below is my code...
$books = array (
"finality"=> array (
"title" => 1,
"author" => 2,
"thumbnail" => 3,
"file" => 4,
"comment" => 5,
),
"science"=> array (
"title" => 1,
"author" => 2,
"thumbnail" => 3,
"file" => 4,
"comment" => 5,
),
"morality"=> array (
"title" => 1,
"author" => 2,
"thumbnail" => 3,
"file" => 4,
"comment" => 5,
),
)
i want to add variables like. $title, $author, $pic2, $pic, $comment, in one array like $books['morality']. please help me.
If I undestand your question correctly, this is what you want.
$books['morality']['title'] = $title;
$books['morality']['author'] = $author;
$books['morality']['thumbnail'] = $pic2;
$books['morality']['file'] = $pic;
$books['morality']['comment'] = $comment;
If that's not what you are looking for try and be more precise in what you want to accomplish.
From what I understand, you would like to add a new item to the array.
Does the following look like what you need? If not, can you please try to clarify what it is that you would like?
$books[ $category ] = array(
"title" => $title,
"author" => $author,
"thumbnail" => $thumbnail,
"file" => $file,
"comment" => $comment
);
Related
I have a deeply nested PHP array which I saved as a document in Mongo and ended up with this structure:
{
"_id" : "...",
"categ1" : {
"aaa" : 112.6736,
"bbb" : 83.9137,
"ccc" : 80.3322,
.....
},
"categ2" : {
"xxx" : 1,
"yyy" : 22,
"zzz" : 7,
"subcateg" : {
"sub1" : 1,
"sub2" : 22
}
}
}
Now, I have another array with a similar structure and I would like to increase the values of the record, by the values of the modifier array:
$modifier=array(
'categ1' => array(
'aaa' => 3,
'bbb' => -1,
'mmm' => 11
),
'categ2' => array(
'yyy' => -2,
'subcateg' => array(
'sub1' => -1
)
)
);
How can I increase the values inside the document by the values of the $modifier all at once, in a single query, and without loading the entire document ?
I've looked around the web but couldn't find any info on this.
Also, i'm pretty newbie at Mongo. Thanks
You can get your $modifier array to look like this:
$modifier = array(
'categ1.aaa' => 3,
'categ1.bbb' => -1,
'categ1.mmm' => 11,
'categ2.yyy' => -2,
'categ2.subcateg.sub1' => -1
)
Link for how to get that.
Then you should be able to simply use:
$col->update(
array("_id" => "..."),
array('$inc' => $modifier),
array("upsert" => true)
);
I have "_id" and "ProductLot". How can I Update Qty "0" to "1 " in the Lot array if ProductLot if present or append a new Lot element if it is not present?
"_id" : ObjectId("5462e44c599e5c6c1300000a"),
"LocationName" : "Putaway",
"Owner" : "",
"Status" : "1",
"Scrap" : "0",
"Lot" : [{
"Qty" :"6",
"ProductLot" : ObjectId("5462dbd9599e5c200e000000"),
"Product" : ObjectId("543ca7be4cf59d400c000004"),
"Movement" :[ {"OriginId" : "266",Qty:2,Type:"DN"},
{"OriginId" : "267" , Qty:1 , Type:"DN"},
{"OriginId" : "2" , Qty:3 , Type:"IM"},
]
},
{
"Qty" :"0",
"ProductLot" : ObjectId("5462dbd9599e5c200e000003"),
"Product" : ObjectId("543ca7be4cf59d400c000004"),
"Movement" :[ {"OriginId" : "266",Qty:2,Type:"DN"},
{"OriginId" : "267" , Qty:1 , Type:"DN"},
{"OriginId" : "2" , Qty:-3 , Type:"IM"},
]
}]
}
EG: I have "ProductLot" : ObjectId("5462dbd9599e5c200e000000") present in array so it should update qty 0 to 1; however, "ProductLot" : ObjectId("5462dbd9599e5c200e00000a") is not available in array so that should append a new element to the array.
PHP code, which is not updating creating appending array at every time:
$inventoryId = new \MongoId($_POST["inventoryid"]);
$productLotId = new \MongoId($invlotid);
$originId = $_POST['id'];
//$lotcontent = [ /* whatever this looks like */ ];
$lotcontent = array(
'Qty' => $invqty,
'ProductLot' => new \MongoId($invlotid),
'Product'=>$invproduct,
'Movement'=> array(
array(
'OriginId' => $_POST['id'],
'Qty' => $invqty,
'Type'=> 'DN',
), )
);
$invcolname = 'Inventory';
$result = $mongo->$dbname->$invcolname->update(
// Match an inventory without the specific ProductLot/OriginId element
array(
'_id' => $inventoryId,
'Lot' => array(
'$not' => array(
'$elemMatch' => array(
'ProductLot' => $productLotId,
//'OriginId' => $originId,
),
),
),
),
// Append a new element to the Lot array field
array('$push' => array( 'Lot' => $lotcontent ))
);
$movementcontent = array(
'OriginId' => $_POST['id'],
'Qty' => $invqty,
'Type'=> 'DN',
);
$result = $mongo->$dbname->$invcolname->update(
// Match an inventory without the specific ProductLot/OriginId element
array(
'_id' => $inventoryId,
'Lot' => array(
//'$not' => array(
'$elemMatch' => array(
'ProductLot' => $productLotId,
'Movement'=>array(
'$not' => array(
'$elemMatch' => array(
'OriginId' => $originId,
)
)
)
),
// ),
),
),
// Append a new element to the Lot.Movement array field
array('$push' => array( 'Lot.$.Movement' => $movementcontent ))
);
$result = $mongo->$dbname->$invcolname->update(
// Match an inventory with a specific ProductLot/OriginId element
array(
'_id' => $inventoryId,
'Lot' => array(
'$elemMatch' => array(
'ProductLot' => $productLotId,
//'OriginId' => $originId,
'Movement'=>array(
'$elemMatch' => array(
'OriginId' => $originId,
)
)
),
),
),
// Update the "Qty" field of the first array element matched (if any)
//array( '$set' => array( 'Lot.$.Qty' => 'Updated' )),
array( '$set' => array( 'Lot.$.Movement.$.Qty' => $invqty )),
array('upsert' => true));
Please anyone help me to resolve this?
Using $addToSet is problematic in this case, because the following lot elements would be considered different:
{
"Qty" :0,
"ProductLot" : ObjectId("5462dbd9599e5c200e000003"),
"Product" : ObjectId("543ca7be4cf59d400c000004"),
"OriginId" : "266"
}
{
"Qty" :5,
"ProductLot" : ObjectId("5462dbd9599e5c200e000003"),
"Product" : ObjectId("543ca7be4cf59d400c000004"),
"OriginId" : "266"
}
The first element is likely what you would be adding (either with quantity 0 or 1), and the second element would be the same logical lot element, just with an incremented quantity. If the latter element already existed in the array, I imagine you'd like for your application to increment the quantity from 5 to 6 instead of adding the first element, which is essentially a duplicate.
We definitely need two updates here, but I would propose the following:
// Let's assume the following identifiers...
$inventoryId = new MongoId($_POST['inventoryid']);
$productLotId = new MongoId($invlotid);
$originId = new MongoId($_POST['id']);
$lotcontent = [ /* whatever this looks like */ ];
$result = $collection->update(
// Match an inventory without the specific ProductLot/OriginId element
[
'_id' => $inventoryId,
'Lot' => [
'$not' => [
'$elemMatch' => [
'ProductLot' => $productLotId,
'OriginId' => $originId,
],
],
],
],
// Append a new element to the Lot array field
[ '$push' => [ 'Lot' => $lotcontent ] ]
);
MongoCollection::update() will return a result document with an n field indicating the number of affected documents. Since we aren't using the multiple option and are also matching at most one document by _id, we can expect n to be either 0 or 1. If n was 0, we either couldn't find an inventory document with that _id or we found one but it already had a Lot element with the product and origin identifiers (i.e. our $elemMatch criteria matched something, invalidating our negation). If n was 1, that means we found the inventory document, it did not contain a matching Lot element, and we appended it (i.e. our job is done).
Assuming n was 0, we should issue another update and attempt to increment the quantity:
$result = $collection->update(
// Match an inventory with a specific ProductLot/OriginId element
[
'_id' => $inventoryId,
'Lot' => [
'$elemMatch' => [
'ProductLot' => $productLotId,
'OriginId' => $originId,
],
],
],
// Update the "Qty" field of the first array element matched (if any)
[ '$inc' => [ 'Lot.$.Qty' => 1 ] ]
);
Here, I'm using the $ positional update operator to access a specific array element that was matched in the criteria. This allows us to craft an $inc without worrying about the index of the matched element.
Again, we can check $result['n'] here. If it's still 0, then we can assume that no document matches our _id (a completely separate error). But if n is 1 at this point, we successfully incremented the quantity and our job is done.
I come here for help with an exercise that I have been racking my brain over for 3 hours now. I have two arrays, $authors and $books.
$authors:
$authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens", "Milton", "Orwell" );
$books:
$books = array(
array(
"title" => "The Hobbit",
"authorId" => 2,
"pubYear" => 1937
),
array(
"title" => "The Grapes of Wrath",
"authorId" => 0,
"pubYear" => 1939
),
array(
"title" => "A Tale of Two Cities",
"authorId" => 3,
"pubYear" => 1859
),
array(
"title" => "Paradise Lost",
"authorId" => 4,
"pubYear" => 1667
),
array(
"title" => "Animal Farm",
"authorId" => 5,
"pubYear" => 1945
),
array(
"title" => "The Trial",
"authorId" => 1,
"pubYear" => 1925
),
);
As you can see, $authors is a two-dimensional indexed array whereas $books is a multidimensional associative array. My task is to create a new key (I think a key? Even the vocabulary for arrays messes me up..) for $books called "authorName", and populate the key with the authors from the $authors array. The catch is that the index for the authors in the $authors array corresponds to the "authorId" in the $books array, however the IDs are out of order.
In other words, my task is to pull the data from the $authors array so that the books array ends up with the following data:
$books = array(
array(
"title" => "The Hobbit",
"authorId" => 2,
"pubYear" => 1937
"authorName" => "Tolkien"
),
array(
"title" => "The Grapes of Wrath",
"authorId" => 0,
"pubYear" => 1939
"authorName" => "Steinbeck"
),
array(
"title" => "A Tale of Two Cities",
"authorId" => 3,
"pubYear" => 1859
"authorName" => "Dickens"
),
...and so on. Any help would be appreciated since I have absolutely no idea how to do this.
Congrats on learning PHP! I'll start with the minor things like vocabulary; I think it's important in programming to get it right ;-)
The $authors array is not two-dimensional
You said it was out of order, but I don't think it is. Keep in mind array indexes are 0-based.
Yes, "key" is an okay way to describe what you are trying to add. Slightly more semantically appropriate might be "entry", where "entry" is comprised of a "key" and it's "value"
Here is some code. I've chosen to be slightly more verbose than I might usually author code in order to be clear what is happening.
foreach($books as $book_index => $book_array) {
// Get the index of the author in the $authors array.
// With this value, $authors[$authorId] will be the name of the author of this book
$authorId = intval($book_array['authorId']);
// this line adds an entry to the current book in the $books array.
$books[$book_index]['authorName'] = $authors[$authorId];
}
You can do it by simply running a loop on $books as followed.
foreach($books as $index => $book){
$books[$index]['authorName'] = $authors[$book['authorId']];
}
The below snippet should do the trick. Iterate over the books array, set authorName equal to the value correspondent to the iteration's book authorId.
foreach($books as $key => $book) {
$books[$key]['authorName'] = $authors[$book['authorId']];
}
So I am trying to make a JSON object that should hold some information about some questions for me. This is a pseudo-code of how I want it to be presented:
{
"page" : 1,
"info" :
{
"id" : 1,
"type" : 3,
"description": "How to do JSON?",
"alternatives" :
{
"id" : 1,
"description" : "Dunno"
}
{
"id" : 2,
"description" : "Let me show you"
}
{
"id" : 3,
"description" : "I refuse to show you"
}
}
"id" : 2,
"type" : 1,
"description": "Do you get it?",
"alternatives" :
{
"id" : 1,
"description" : "Yes"
}
{
"id" : 2,
"description" : "No"
}
}
}
So the code underneath is from Nightmare (one of the answers), and it does exactly what I want to do with the page and the questions, but I can't seem to figure out how to connect alternatives to each question. You can see a snippet at the bottom where I have tried but it's not correctly spelled and I've been hammering at this for a while now.
$before_json_encode[$row['page']][] = array(
'id' => $row['id'],
'type' => $row['type'],
'description' => $row['description'],
'alternatives' => $alternativesarray//im not sure about here,dont know the structure of the alternative array
);
Another illustration on how I want the hierarchy of the JSON data to appear. I need to be able to pick for instance: All alternatives to all questions on a specific page. So if I want to generate page 3 in my poll I can first find the questions within the page 3 sub-array, and then again from each question gain access to all of it's connected alternatives in that questions's own sub-array. Sorry for the poor explanation of my issue, it's just a bit complicated :/
Page
Question
Alternative
Alternative
Alternative
Question
Alternative
Alternative
Alternative
Question
Alternative
Alternative
Page
Question
Alternative
Alternative
Question
Alternative
Alternative
Update: 3rd layer:
$rows_test2[$r['page']]
['id' => $r['id'],
'type' => $r['type'],
'description' => $r['description']]
[] =
array (
'altid' => $t['altid'],
'altdesc' => $t['altdesc']);
$rows[] = array(
"page" => 1,
"info" => array(
"id" => 1,
"type" => 3,
"description" => 'desc',
)
);
echo json_encode($rows); // [{"page":1,"info":{"id":1,"type":3,"description":"desc"}}]
Update:
$alternativesarray[]=array('id'=>'1', 'description'=>'yes');
$alternativesarray[]=array('id'=>'2', 'description'=>'no');
$rows[] = array(
"page" => 1,
"info" => array(
"id" => 2,
"type" => 3,
"description" => 'desc',
"alternatives" => $alternativesarray
)
);
print json_encode($rows); // [{"page":1,"info":{"id":2,"type":3,"description":"desc","alternatives":[{"id":"1","description":"yes"},{"id":"2","description":"no"}]}}]
maybe like this?
$before_json_encode[$row['page']][] = array(
'id' => $row['id'],
'type' => $row['type'],
'description' => $row['description'],
'alternatives' => $alternativesarray//im not sure about here,dont know the structure of the alternative array
);
Trying to push some data to record using php
array('$push' => array(
"value" => 1,
"comment" => $data['comment'],
"status" => 1,
))
But in db I see following records like array :
And it's should be like a normal values :
Seems that you want to use $set instead of $push.
array('$set' => array(
"value" => 1,
"comment" => $data['comment'],
"status" => 1,
))
$push is for appending elements to embedded arrays. $set is for replacing field values.