get mongoDB embedded document array value using php? - php

How to get the contact values?, and How are the values stored in php?
{
_id : "001",
name : "fakename",
contact_address : {
street : "12 Street",
city : "Cosmos",
contact : [
"123456789",
"012345678"
]
}
}
Query :
$cursor = $collection->find ( array('name' => 'fakename' ), array( 'contact_address.contact' ) );
foreach ( $cursor as $doc ) {
echo $doc[ 'contact_address' ][ 'contact' ];
}
Result :
Array
Motive : Intend to print the contact values.

To print array values you can use print_r, var_dump or var_export - for debugging purposes.
To iterate them and use values in other places - you can use for example foreach like that:
foreach ($array as $key => $value) {
// $key holds the index, $value holds the value of the array
}
There are other ways to iterate array, in fact way too many in PHP, but this should suffice.

Related

How to check if array contains certain value for specific key when the parent array is not associative?

I have the following array that contains associative arrays:
array(
[0] => array ("name" => "foo", //more key-value pairs)
[1] => array ("name" => "bar", //more key-value pairs)
[2] => array ("name" => "baz", //more key-value pairs)
)
How can I check if a name exists while iterating over another array of names:
foreach ($list_of_names as $name) {
// does the current name exist in the other array?
}
Is there a way to do it without nesting foreach loop inside the foreach loop?
Your question is a bit vague. I understand that you ask whether it is possible to check if any of the inner arrays contains a given key without using two nested foreach loops.
If so then take a look at this example:
<?php
$data = [
["name-foo" => "foo"],
["name-bar" => "bar"],
["name-baz" => "baz"],
];
$needle = "name-bar";
array_walk($data, function($entry) use ($needle) {
var_dump(
array_key_exists($needle, $entry)
? "$needle exists"
: "$needle does NOT exist"
);
});
The output obviously is:
string(23) "name-bar does NOT exist"
string(15) "name-bar exists"
string(23) "name-bar does NOT exist"
In the end there is no way around having to iterate over all entries in the nested arrays. But you don't have to do that explicitly in the calling scope, you can use the many convenience functions php offers, here array_key_exists(...) for example.
If you just need to know if the name exists, you could extract the name values (using array_column()) and (in this case) using aray_flip() to make it an associative array. This allows you to use isset() inside the loop and not have to do any nested loops.
$data = [
['name' => 'foo'], //more key-value pairs)
['name' => 'bar'], //more key-value pairs)
['name' => 'baz'], //more key-value pairs)
];
$list_of_names = [
'foo',
'bart'
];
$dataNames = array_flip(array_column($data, 'name'));
foreach ($list_of_names as $name) {
if (isset($dataNames[$name])) {
echo "$name exists" . PHP_EOL;
} else {
echo "$name does not exist" . PHP_EOL;
}
}
will show
foo exists
bart does not exist

Foreach items if item is from one of the type/category

I'm looking to foreach items from php array where type is the "key".
Show all items where one of the type is type-2.
Thank you
<?php $gallery = [];
$gallery [1] = [
"Name" => "Three Full Length Mirrors",
"Description" => "Three mirrors with silver aluminum profile. ",
"image" => "full-mirror.jpg",
"type" => [
"type-1",
"type-2",
"type-3"
]
];
?>
You could use array_filter to pre-filter the array, but it's just as easy to put the test in your foreach loop:
foreach ($gallery as $g) {
if (!in_array('type-2', $g['type'])) continue;
// rest of code
}
<?php
$result = array_filter($gallaries, function($gallery){
// If below is true element stays, the false cases get removed from array
return in_array('type-2',$gallery['type'])
});

PHP getting dynamic $_POST content

So I'm trying to get dynamic data from the $_POST array. The $_POST array looks like this after the form submit:
Array
(
[teams1member3] => on
[teams1member4] => on
[teams1member7] => on
[teams1member8] => on
[teams2member1] => on
)
Now I'm not entirely sure how I can access these, the teams can be any number and the same goes for a member. Is there a way to "read" the [teams1member3]?
I tried looping through the $_POST variable with a foreach loop (foreach($_POST as $post)), but this only gets the value (on). If I'm able to get the teams1member3, teams1member4, etc. I should be able to continue.
Anyone that can help me out? Much appreciated!
You should use the $key => $value syntax:
foreach($_POST as $key => $post){
// $key is what you need
}
But you should rather serialise your $_POST data better, consider using the following JSON notation:
{
"teams" : [
{
"id": 1,
"members": [3, 4, 7, 8]
},
{
"id": 2,
"members": [1]
}
]
}
foreach ($_POST as $key => $value) {
// ...
}
$key will contain array keys (what you need), $value - string "on".
if you just use foreach($_POST as $value) , you will only get the values - in your case on and off
However, if you want the actual field name, you have to specify key and value in your foreach:
foreach($_POST a $key => $value) {
//$key contains teammember
//$value contains on
}

PHP array loop and format

I am very new to PHP, learning fast but not fast enough! I am also learning Laravel 5.1.
I am trying to build a HTML select list array from an Eloquent query output, in the correct format for form builder (Form::select).
I have the following call to Eloquent to pull the data:
// Get list of States for address select
$states = State::all()->toArray();
It returns the following array:
array:8 [▼
0 => array:2 [▼
"id" => "1"
"state" => "ACT"
]
1 => array:2 [▼
"id" => "2"
"state" => "NSW"
]
...
];
I want to loop through it and generate the following output:
array = [
'' => 'State', <-- This is the default for the select list
'1' => 'ACT',
'2' => 'NSW',
...
];
I am using Laravel 5.1, so I am using the included array_add() function in my helper.
I call my function like this:
$states = create_select_list($states, 'State');
I next want to format the output so it is ready for the Form::select statement. I have tried the code below (as the final try from a few iterations!) but unsuccessfully.
function create_select_list($data, $default)
{
// Declare array and set up default select item
$container = ['' => $default];
// Loop through data entries and build select list array
foreach($data as list($entry, list($key, $value))) {
$container = array_add($container, $key, $value);
}
// Return the select list array
return $container;
}
All help or suggestions are appreciated!
This answer is not about loop fix. I think previous comment should help you.
Just another idea. You can try use array_map instead foreach for this case.
For example:
$states = ['' => 'State'];
array_map(function($item) use (&$states) {
$states[$item['id']] = $item['state'];
}, State::all()->toArray());
Loop like below:
foreach($data as $key => $keyArr ) {
$container = array_add($container, $keyArr['id'], $keyArr['state']);
}
You don't need to use list() in your foreach loop, instead try:
foreach($data as $key => $value) {
$container = array_add($container, $key, $value);
}
The PHP documentation gives a good overview of what list() actually does.

How to replace an element in an array

I have a COLLECTION collflokks in MongoDB, sample Document is :-
{
"_id" : "b_8AUL",
"f_name" : "Pizza. Hut",
"f_lat" : "22.7523513",
"f_lng" : "75.9225847",
"c_uid" : "33",
"f_type" : NumberLong(3),
"members" : [
"42",
"43"
]
}
Within the "members" array , I want to add Arrays like {id:42,name:Mark} , {id:43,name:Hughes}
Currently i'm adding just ids(eg.42,43). I'm only concerned about the new data as it will have new ids .Please suggest.
Earlier I was using this code to push into the members Array:
$flokkCollection = 'collFlokks';
$flokkCollection->update(
array("_id" => $f_handle),
array('$push' => array("members" => $u_id))
);
Well if what you are asking here is "replacing your existing data" then you need to "loop" the results from the collection and "replace" the array content that exists with your new format.
There are likely smarter ways to approach this, but you are not really giving us all the required information in your question, so I can only answer in the basic terms.
Presuming you have:
$required = array(
array(array("id" => "42"), array("name" => "Mark")),
array(array("id" => "43"), array("name" => "Hughes"))
);
As input, then you do something like this:
function myMapper($v) {
return $v["id"];
}
$mapped = array_map("myMapper",$required);
foreach( $mapped as $value) {
$filtered = array_values(
array_filter($required,function($k) {
return $k["id"] == $value;
})
)[0];
collection.update(array(
array("members" => $value),
array('$set' => array(
"members.$" => $filtered
))
));
}
Which should use the positional $ operator to find the matched "position" of the array element by the value used in the "query" portion of the update statement, then in the "update" portion of that statement $set that current array index to the new value at the "filtered" content index from the original input array.
Outside of PHP. We call these inner elements "objects" and not "arrays" which is a PHP notation trait. Key/value things are "objects" and "lists" are "arrays".

Categories