PHP Mongodb create Text Index - php

I am new in MongoDB, and I'm trying to create a text index.
After trying several hours, I have not accomplished anything.
I have an array like this:
//The keys and values are reversed to avoid duplicates in the array keys.
$arr = array(
'Personal' => array(
'PEPE' => "_id",
'd' => array(
"full_name" => "Pedro",
"last_name" => "Picapiedras",
"address"=> "La matanza 123",
"department"=> "Soporte"
), //d end
'PABLO' => "_id",
'd' => array(
"full_name"=> "Pablo",
"last_name"=> "Marmolejo",
"address"=> "Pica 123",
"department"=> "Soporte"
), //d end
)//personal end
);//arr end
I want to create an Index of the _id field so that to edit or view documents, access them through "Pablo" or "Pepe".
Is this possible? Could you give me a hand on how I can do this?
Edit
I have tried with
db.reviews.createIndex( { comments: "text" } )
and
$user = Array(
'_id' => "$id",
'name' => $name,
);
$query = Array( '_id' => "$id" );
$query = Array( '_id' => new MongoId("$id") );

Try this:
$arr = array(
'PEPE' => array(
"_id" => 'PEPE',
'd' => array(
"full_name" => "Pedro",
"last_name" => "Picapiedras",
"address" => "La matanza 123",
"department" => "Soporte"
) //d end
), //PEPE END
'PABLO' => array(
"_id" => 'PABLO',
'd' => array(
"full_name" => "Pablo",
"last_name" => "Marmolejo",
"address" => "Pica 123",
"department" => "Soporte"
), //d end
) // Pablo END
); //$arr end
function insertMongo($array) {
try {
$mongo = new MongoClient();
$db = $mongo -> dbName;
$collection = $db -> collectionName;
$collection -> insert($array);
} catch (MongoCursorException $e) {
die("Query failed ".$e - > getMessage());
}
} //insertMongo
//To execute:
foreach($arr as $a) {
insertMongo($a);
};

Related

how to make a new php array with merge fields and change name attributes

i am try change a array in php in laravel. i have a nested array with duplicate fields. but there is one i what to change the name timestamp. how can i do this?
$consumos = array(
array(
"device" => "EA1",
"timestamp" => "2020-01-01 21:00:00",
"value" => 4,
),
array(
"device" => "EA1",
"timestamp" => "2020-01-01 07:00:00",
"value" => 4,
),
array(
"device" => "EA2",
"timestamp" => "2022-01-01 12:00:00",
"value" => 2,
),
array(
"device" => "EA2",
"timestamp" => "2022-01-01 13:00:00",
"value" => 2,
),
);
i what to make something like this:
array(
"device" => "EA1",
"start" => "2020-01-01 21:00:00",
"end" => "2020-01-01 07:00:00",
"value" => 4,
),
array(
"device" => "EA1",
"start" => "2022-01-01 12:00:00",
"end" => "2022-01-01 13:00:00",
"value" => 2,
),
thanks in advance!
I'm not sure if the 'grouping key' is the device, the value, or both, but anyway.
I'd use a for-loop to map it, then drop the keys from the map:
$map = [];
foreach ($consumos as $consumo) {
$key = $consumo["device"]; // or value, or both
if (isset($map[$key])) {
$map[$key]["end"] = $consumo["timestamp"];
} else {
$map[$key] = [
"device" => $consumo["device"],
"start" => $consumo["timestamp"],
"value" => $consumo["value"],
];
}
}
$return = [];
foreach ($map as $ret) {
$return[] = $ret;
}
If you know you'll always have an even number of events per key, and there can be more than two events per key, you could merge both foreach, and make it so when you add an 'end' timestamp, you also add the element to $return and drop the element from the map (allowing it to be inserted again when it shows up).
$map = [];
$return = [];
foreach ($consumos as $consumo) {
$key = $consumo["device"]; // or value, or both
if (isset($map[$key])) {
$map[$key]["end"] = $consumo["timestamp"];
$return[] = $map[$key];
unset($map[$key]);
} else {
$map[$key] = [
"device" => $consumo["device"],
"start" => $consumo["timestamp"],
"value" => $consumo["value"],
];
}
}
first, try using a grouping array based on the device name, you can use this page for sample algorithm: url
then with a foreach loop, you can get each timestamp of the device name and you can add devices to an array like this :
$newArray[] = [
// other fields ...
"start" => $item[0]['timestamp'],
"end" => $item[1]['timestamp'],
]

PHP create value variable for json_encode function

I'm using a JSON API; I want to create a variable with values and then convert it to a JSON string via json_encode. The (working) JSON string is this:
$data = '
{
"function":"setArticleImages",
"paras":{
"user":"'.$user.'",
"pass":"'.$pass.'",
"product_model":"'.$productsModel.'",
"images":{
"products_id":'.$products_id.',
"image_name":"'.$imageName.'",
"image":"'.$image.'",
"products_images":[{
"products_id":'.$products_id.',
"image_name":"'.$imageName2.'",
"image":"'.$image2.'"
} ]
}
}}
';
I was now trying to write it like this and use json_encode:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
),
)
)
);
$data = json_encode($data);
Unfortunately it does not work. The problems seems to be at '"products_images" => array('. I don't know how to handle the '[' of the '"products_images":[{' part.
Anyone an idea how to write it in the second code snippet?
You just need to add an extra level of array to the products_images element, so that you get a numerically indexed array of associative arrays, giving you the array of objects form you want:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
)
),
)
)
);
Demo on 3v4l.org
The "{ }" in th JSON notation is a PHP array with alphanumerical key.
So :
$array = ["foo" => [1,2,3], "bar" => [4,5,6]
will be converted in a JSON string :
{ foo : [1,2,3], bar: [4,5,6]}
So if you are looking to a JSON that looks like this
[{ foo : [1,2,3], bar: [4,5,6]}]
You will have to do an array with numeric keys that contains your alphanumerical array :
$array = [["foo" => [1,2,3], "bar" => [4,5,6]]];
// same as
$array = [ 0 => ["foo" => [1,2,3], "bar" => [4,5,6]]];

PHP - Push data to array in foreach loop [duplicate]

This question already has answers here:
PHP Append an array to a sub array
(2 answers)
Closed 2 years ago.
I want to achieve below array format:
{
"success": true,
"results": [
{
"name" : "Choice 1",
"value" : "value1",
"text" : "Choice 1"
},
{
"name" : "Choice 2",
"value" : "value2",
"text" : "Choice 2"
}
]
}
However, I am using PHP and a foreach loop, to return some values from my database:
//Search for clients in our database.
$stmt = $dbh->prepare("SELECT * FROM customers");
$stmt->execute();
$showAll = $stmt->fetchAll();
I then have my first part of the array, and my foreach loop:
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data_array[] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
Above only outputs:
[
{
"name":"Choice 1",
"value":"value 1",
"text":"Choice 1"
},
{
"name":"Choice 2",
"value":"value2",
"text":"Choice 2"
}
]
So it is missing the top part of my original array - but I want to loop through each database results in "results": [ ... ]
Try this
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data['results'][] = array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
$data['success'] = true; // if you want to update `status` as well
echo json_encode($data);
After creating $data_array array just add few lines which i have in my post.
Try this code snippet here(with sample input)
ini_set('display_errors', 1);
foreach ($showAll as $client)
{
$data_array[] = array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
// add these lines to your code.
$result=array();
$result["success"]=true;
$result["results"]=$data_array;
echo json_encode($result);
try this as you have an array inside the $data_array on Key "Results" so you should use "results" as a key also and then try to push data in that array
foreach ($showAll as $client) {
$data_array["results"][] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
You can simply use json_encode and push it to your result array
$data = array(
"success" => false,
"results" => array()
);
$result = [
[
"name" => "Choice 1",
"value" => "value 1",
"text" => "Choice 1"
],
[
"name" => "Choice 2",
"value" => "value2",
"text" => "Choice 2"
]
];
$data['results'] = json_encode($result);

PHP array_intersect / array_diff / combine array

$arr[] = array('title' => 'Overview');
$arr[] =array('title' => 'General');
$arr[] =array('title' => 'History');
$arr[] =array('title' => 'Construction');
$arr[] =array('title' => 'Plan');
$arr[] =array('title' => 'Other');
$info_arr[] = array("title" => "General", text => "value1");
$info_arr[] = array("title" => "History", text => "value1");
$info_arr[] = array("title" => "Construction", text => "value1");
$info_arr[] = array("title" => "Plan", text => "value1");
I need to be able merge these arrays together.So they look something like this. As I will need to loop thru the consolidated array. Other, Overview do not have any text values but still need to placed into the array.
$new_arr[] = array("title" => "General", text => "value1", "title" => "History", text => "value1", "title" => "Construction", text => "value1"
,"title" => "Plan", text => "value1","title" => "Overview", text => "","title" => "Other", text => "");
I have tried for loops (using count value), foreach loops, I thought array_intersect or array_diff don't see to solve the issue. This should not be so difficult, but I'm trying to piece together some really bad legacy code. Or the cube/florescent lights might have finally got to me.
Update:
while ($stmt->fetch()) {
$arr[] = array("title" => $Title);
}
and
while ($dstmt->fetch()) {
$info_arr[] = array("title" => $descriptionType, "descriptiontext" => $descriptionText); , "descriptiontext" => $val );
}
$dstmt & $stmt are queries.
I thought this would work but not so much
$r = array_intersect($arr, $info_arr);
var_dump($r);
Something like this Let me clarify:
$new_arr = array(array("title" => "General", text => "value1"),
array("title" => "History", text => "value1"),
array("title" => "Construction", text => "value1"),
array("title" => "Plan", text => "value1"),
array("title" => "Overview", text => ""),
array("title" => "Other", text => "")
);
If you want to work with these two arrays, you can just use the title as the key in $r.
foreach (array_merge($arr, $info_arr) as $x) {
$r[$x['title']]['title'] = $x['title'];
$r[$x['title']]['text'] = isset($x['text']) ? $x['text'] : '';
}
Or, you can go back a step and avoid having separate arrays by building the $r array in the same manner as you fetch your query results:
while ($stmt->fetch()) {
$r[$Title] = array('title' => $Title, 'text' => '');
}
while ($dstmt->fetch()) {
$r[$descriptionType] = array("title" => $descriptionType, "text" => $descriptionText);
}
Or, ideally, you could go back another step and avoid having separate queries by using a JOIN to get the same results in one query, but there's nothing in the question on which to base any specific suggestion for that.
As stated in the comments, the exact $new_arr you're requesting isn't possible. However, I think this will give you a similar result that should work for your purposes:
foreach ($info_arr as $infoArray) {
$found = array_search(array('title' => $infoArray['title']), $arr);
if (false !== false) {
unset($arr[$found]);
}
}
$new_arr = array_merge($info_arr, $arr);
It works by removing the "duplicates" from the original $arr before doing the array_merge().
If it's important to add an empty text value for the remaining items in $arr, do this before the array_merge():
foreach ($arr as &$arrArray) {
$arrArray['text'] = '';
}
The resulting array will look like this:
$new_arr[] = array(
array(
'title' => 'General',
'text' => 'value1',
),
array(
'title' => 'History',
'text' => 'value1',
),
array(
'title' => 'Construction',
'text' => 'value1',
),
array(
'title' => 'Plan',
'text' => 'value1',
),
array(
'title' => 'Overview',
'text' => '',
),
array(
'title' => 'Other',
'text' => '',
),
);

Appending an array to a multi dimensional array fails silently PHP?

I am trying to append an array to another one in a multi dimensional array:
This is the multi dimensional array:
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
I has a key which is the master id, and a master item which is an array with a name and another array with the detail (at the first time is empty).
But when I try to add to the $info['master']['detail'] array another array with a detail, like this:
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
Nothing is added... How is that possible?
EDIT: the foreach loops that should add the details to the master:
foreach ($details as $detail)
{
$name = $detail['detail_name'];
$value = $detail['detail_value'];
if ($info['key'] == $detail['id']) {
$info['master']['detail'][] = array("name" => $name,
"value" => $value);
}
}
I'm not sure I understand but when I see your examples, I think it is a problem of index:
Try to replace
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
by
$info = array( 'key' => $row['id'],
'master' => array('name' => $row['master_name'],,
"detail" => array())
);
$info['master']['detail'] = array("name" => "A detail name",
"value" => "A detail value");
and to add a new value :
$info['master']['detail']['foo'] = "A detail foo";

Categories