How to use the function inside the json_decode() using ci - php

Here i have one array, in this array i have one more array called studentabsentId,
public function admin_getabsentlist()
{
$data = array(
"schoolId" => $_POST['schoolName'],
"classId" => $_POST['className'],
"sectionId" => $_POST['sectionName'],
"absentDate" => date("Y-m-d", strtotime($_POST['absentDate']))
);
$absentresponse= $this->Admin_attendance_model->admin_options_listdisplay($data);
$optionsList = array();
foreach($absentresponse as $hmres)
{
$hmparent['studentabsentId']=json_decode($hmres['studentAbsentId']);
$hmparent['studentAbsentDate']=$hmres['studentAbsentDate'];
array_push($optionsList,$hmparent);
}
//echo $json = json_encode($optionsList);
$return = array("status" => 1, "data" => $optionsList);
echo json_encode($return);
}
echo json_encode($return);
{
"status": 1,
"data": [
{
"studentabsentId": [
"1"
],
"studentAbsentDate": "2017-04-12"
}
]
}
upto now its working fine,now what i want means,studentabsentId 1 means what is his name,suppose studentabsentId 2 means what is name, for that purpose i written the function called getStudentnameById in helper/custom_helper.php.
So in my for each loop i added one more line like this
$hmparent['studentabsentName']=json_decode(getStudentnameById($hmres['studentAbsentId']));
But now i am getting the error of Undefined offset: 0,how can solve this error and , how to display the name
custom_helper.php
if ( ! function_exists('getStudentnameById')){
function getStudentnameById($id){
$ci =& get_instance();
$ci->load->database();
$ci->db->select('firstName');
$ci->db->where('student_id', $id);
$q = $ci->db->get('new_student')->result();
return $q[0]->firstName; // particulart filed
}
}
My updated code
print_r($absentresponse);
Array
(
[0] => Array
(
[absendId] => 2
[studentAbsentId] => ["1"]
[studentAbsentDate] => 2017-04-12
[schoolId] => 2
[classId] => 1
[sectionId] => 1
[reg_date] => 2017-04-13 01:01:14
[created_by] => kanniyappan#g2evolution.co.in
[status] => 0
)
)
Expected Results
{
"status": 1,
"data": [
{
"studentabsentId":"1"
"studentabsentName":"Kani"
"studentAbsentDate": "2017-04-12"
}
]
}

Your getStudentnameById returns a string supposedly, so why are you doing a json_decode on top of that. $hmparent['studentabsentName']=json_decode(getStudentnameById($hmres['studentAbsentId']));
Also check the return by that function. You should be able to debug this kind of code if you turned on your error_reporting which tells you the line at which error occurred, then var_dump all the variables that's relevant to it.

Related

How to extract each level in nested array to separated arrays with specific key-value pairs?

I've got a 4-level nested array, each level represent a hiereachy in an organization. Each level's key is the hierarchy value, and inside it there is the id of it in the array. The last level is only the value-id pair:
$data = [
"top_level_data1" => [
'top_level_id' => 0,
'sub_level_1' => [
'sub_level_1_id' => 0,
'sub_level_2_data1' => [
'sub_level_2_id' => 0,
'sub_level_2_data' => [
0 => "some_val"
1 => "some_other_val"
]
]
]
],
"top_level_data2" => [
'level_1_id' => 1,
'sub_level_1_other' => [
'sub_level_1_id' => 1,
'sub_level_2_data2' => [
'sub_level_2_id' => 1,
'sub_level_3_data1' => [
2 => "another_val"
3 => "bar"
4 => "foo"
]
],
'sub_level_2_data3' => [
'sub_level_2_id' => 2,
'sub_level_3_data2' => [
5 => "foobar"
6 => "hello"
7 => "goodbye"
]
]
]
]
];
I want to extract it to separate arrays that would contain the hierarchy value-id pairs.
Expected output from the above example (without the ids of the above level):
$top_level = [
0 => "top_level_data1",
1 => "top_level_data2"
]
$sub_level_1 = [
0 => "sub_level_1",
1 => "sub_level_1_other"
]
$sub_level_2 = [
0 => "sub_level_2_data1",
1 => "sub_level_2_data2",
2 => "sub_level_2_data3"
]
$sub_level_3 = [
0 => "some_val"
1 => "some_other_val"
2 => "another_val"
3 => "bar"
4 => "foo"
5 => "foobar"
6 => "hello"
7 => "goodbye"
]
I've tried using the RecursiveIterator but that does not work (At first I wanted to use it just to check if it iterates correctly, even before assignting the key-values as I wanted, but it just doesn't do it as I wanted):
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach($it as $key => $val) {
$level[$it->getDepth()][] = $val;
}
This can do it:
$result = [];
$recursive = null;
$recursive = function($args,$level=0) use (&$recursive,&$result){
foreach($args as $k=>$v){
if(is_array($v)){
$result[$level][]=$k;
$recursive($v,$level+1);
} else if(is_string($v)){
$result[$level][]=$v;
}
}
};
$recursive($data);
var_export($result);
But your expected output isn't ok. Because i think sub_level_2_data must be sub_level_3_data (in the $data array above). And the hole sub_level_3*level is missing in your expected output.
With this code you get an result array instead of separate filled variables.
Will not explain it in detail, but try to understand whats happening here and you can learn some new php stuff.

Not able to update the inventory stock with patch/put listing Amazon SP API with PHP

I need your help, I tried all the mentioned suggestions (https://github.com/amzn/selling-partner-api-docs/issues/2167) but am still not able to update the inventory quantity with Amazon SP API.
I am trying to update the quantity stock without Feeds.
Below body, I am sending to update the quantity with Put Request.
The package I am using is: https://github.com/jlevers/selling-partner-api
SellingPartnerApi\Model\ListingsV20210801\ListingsItemPutRequest Object
(
[container:protected] => Array
(
[product_type] => FALSE_EYELASH
[requirements] =>
[attributes] => Array
(
[fulfillment_availability] => Array
(
[fulfillment_channel_code] => AMAZON_JP
[quantity] => 5
)
)
)
)
When I use sandbox get a response ACCEPTED but without getting an error.
........
[sku] => 2629-48KGT-2347 // TEST
[status] => INVALID
[submission_id] => 602b84b73b964e24b174a80d3a7870a3
[issues] => Array
(
[0] => SellingPartnerApi\Model\ListingsV20210801\Issue Object
(
[container:protected] => Array
(
[code] => 4000003
[message] => ������������Amazon������������������������������������������������������������������������������
[severity] => ERROR
[attribute_names] =>
)
)
)
........
=======================
To patch the request I am trying the below body.
SellingPartnerApi\Model\ListingsV20210801\ListingsItemPatchRequest Object
(
[container:protected] => Array
(
[product_type] => FALSE_EYELASH
[patches] => Array
(
[op] => replace
[operation_type] => UPDATE // Already try with or without this parameter
[path] => /attributes/fulfillment_availability
[value] => Array
(
[fulfillment_channel_code] => AMAZON_JP
[quantity] => 5
)
)
)
)
Get the below response.
Exception when calling: [400] {
"errors": [
{
"code": "InvalidInput",
"message": "Request has missing or invalid parameters and cannot be parsed.",
"details": ""
}
]
}
Is there any way to update the order status to shipped without the feeds API?
The code which I try so far is below.
$patchBody = [
'product_type' => 'BEAUTY',
'marketplaceIds' => ['A1VC38T7YXB528'], // Already try with or without
'patches' => [
[
"op" => "replace",
"operation_type" => "PARTIAL_UPDATE",
"path" => "/attributes/fulfillment_availability",
"value" => [
[
"fulfillment_channel_code" => 'DEFAULT',
"quantity" => 2
]
]
]
]
];
$putBody = [
'product_type' => 'BEAUTY',
'attributes' => [
"fulfillment_availability" => [
"fulfillment_channel_code" => "DEFAULT",
"quantity" => 2
]
]
];
$seller_id = 'MY-SELLER-ID';
$sku = '8001025974';
$marketplace_ids = array('A1VC38T7YXB528');
// Update inventory
$apiInstance = new SellingPartnerApi\Api\ListingsV20210801Api($config);
$body = new \SellingPartnerApi\Model\ListingsV20210801\ListingsItemPatchRequest($patchBody);
// $issue_locale = 'en_US';
try {
$result = $apiInstance->patchListingsItem($seller_id, $sku, $marketplace_ids, $body);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling: ', $e->getMessage(), PHP_EOL;
}
I found the solution the main issue is in the body there are many different methods which are provided by amazon feed base or listing put/patch base.
In my question, I was using the Listing base approach.
The endpoint URL is below.
{{fe_url}}/listings/2021-08-01/items/{{seller_id}}/8001025974?marketplaceIds={{jp_market_id}}
The body should be like the below. If there is an error in product type even if you pass the current product type just use "PRODUCT" instead.
Note: But if you are using a feed document then it might be changed see here
I got success with the below body.
{
"productType": "PRODUCT",
"patches": [
{
"op": "replace",
"operation_type": "PARTIAL_UPDATE",
"path": "/attributes/fulfillment_availability",
"value": [
{
"fulfillment_channel_code": "DEFAULT",
"quantity": 0
}
]
}
]
}

laravel - Can I add new items to an array that already has some existing items?

var_export($response) is an array like below:
array (
0 =>
array (
'courseId' => 14,
'tutorName' => 'admin',
),
1 =>
array (
'courseId' => 15,
'tutorName' => 'merl',
),
)
The below code gives a result like this: "data": 3. I wanted add a new item called points with the $response array, into all elements. But here, it overwrites the existing array. How can I achieve this?
$dat=array_push($response,array('points'=>"3"));
return response()->json(['data' => $dat], 200);
Expected output:
[
{
"courseId": 14,
"tutorName": "admin",
"points": 3
},
{
"courseId": 15,
"tutorName": "merl",
"points": 3
}
]
As mentioned, array_push() returns the new number of elements in the array. That's why you get 3.
You can add your value in all elements of the current response, like this:
foreach ($response as $key => $value) {
$response[$key]['points'] = 3;
}
Then, just return the response :
return response()->json($response, 200);

Elasticsearch index_options=docs for text data type does not return any search results

I have been using Elasticsearch 7.6 and PHP client API for all the operations.
I have created elasticsearch index settings and mappings as follows
$params = [
'index' => 'elasticindex',
'body' => [
'settings' => [
"number_of_shards" => 1,
"number_of_replicas" => 0,
"index.queries.cache.enabled" => false,
"index.soft_deletes.enabled" => false,
"index.requests.cache.enable" => false,
"index.refresh_interval" => -1
],
'mappings' => [
'_source' => [
"enabled" => false
],
'properties' => [
"text" => [
"type" => "text",
"index_options" => "docs"
]
]
]
]
];
I was able to index document using the following code
$params = array();
$params['index'] = 'elasticindex';
for($i = 1; $i <=2; $i++) {
$params['id'] = $i;
$params['body']['text'] = 'apple';
$responses = $client->index($params);
}
But when I use the following search query
$params = [
'index' => 'elasticindex',
'body' => [
'query' => [
'match' => [
"text" => "apple"
]
]
]
];
$results = $client->search($params);
I am getting empty results as follows
Array
(
[took] => 3
[timed_out] =>
[_shards] => Array
(
[total] => 1
[successful] => 1
[skipped] => 0
[failed] => 0
)
[hits] => Array
(
[total] => Array
(
[value] => 0
[relation] => eq
)
[max_score] =>
[hits] => Array
(
)
)
)
Without creating a static index template, if I try to index, elasticsearch dynamic mapping works well and I am getting the results.
The goal is that I want the elasticsearch to index only document id in its inverted index and not position or offset and I want to retrieve only matching document ids as results. Help is much appreciated. Thanks in advance!
Since the document is being returned by the get handler and not the query handler, your index is not being refreshed properly after indexing the document.
As you noted yourself, in your configuration you set:
"index.refresh_interval" => -1
.. which means that the index is not being refreshed automagically. There's seldom a need to change the refresh interval, except in very high throughput situations or where a particular behavior is wanted.
Try to index doc something like this.
$client = Elasticsearch\ClientBuilder::create()
->setHosts($hosts)
->build();
$params = [
'index' => 'elasticindex',
'type' => 'documents',
'id' => '1',
'body' => ['text' => 'apple']
];
$response = $client->index($params);
print_r($response);
Note: _id you can define dynamically if you want, else id will automatically set by elastic.
And try to get doc via a search query.
{
"query": {
"bool": {
"must": {
"term": {
"text": "apple"
}
}
}
}
}
If you want full-text search on this key, set this key property as
"properties": {
"name": {
"type": "text"
}
}

MongoDB\Driver php How to make inner join with filter in the first collection

I need to make a join between two collections at the same time i need to execute filter for the first collection , exemple :
... // code inside my classe
$this->MDBManager = new MongoDB\Driver\Manager("mongodb:// xxxxx: xxxxx #" . $this->host);
$filter = array ("date", array('$gte' =>str_replace("-","/", "2019-10-5") , '$lte' => str_replace("-","/", 2019-10-15)))
$this->MDBQuery = new MongoDB\Driver\Query($filters, $options);
$this->results = $this->MDBManager->executeQuery("mydb.colllection1", $this->MDBQuery);
so this is my first collection and i need to join the soconde collection id to matche the same value of productEnsembleId attribute in collection 1.
The join request need to be in only one request .
Thnak you so much for your help .
For more details :
exemple collection 1 :
{
"_id": "5db8683c877c34001559f192",
"id": "1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396",
"userId": "DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000",
"productEnsembleId": "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"date": "2019/11/01",
"status": "En cours"
}
exmple collextion 2 :
{
"_id": "5da8948e877c34001529a7f2",
"id": "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"name": "ensemble 2",
"image": "fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177",
"produits": null
}
So assuming you want the join results for one document in the first collection, here is a mongo shell query.
db.col1.aggregate([
{ $match: { "_id": "5db8683c877c34001559f192" } },
{ $lookup: {
from: "col2",
localField: "productEnsembleId",
foreignField: "id",
as: "col2_data"
}
}
])
The results look like ...
{
"_id" : "5db8683c877c34001559f192",
"id" : "1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396",
"userId" : "DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000",
"productEnsembleId" : "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"date" : "2019/11/01",
"status" : "En cours",
"col2_data" : [
{
"_id" : "5da8948e877c34001529a7f2",
"id" : "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"name" : "ensemble 2",
"image" : "fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177",
"produits" : null
}
]
}
which is a combination of collection 1 and collection 2. If you want all records from collection 1 simply remove the $match criteria.
Edit: Include PHP version of same query above...
To use this query in a PHP page see below. This example assumes using the latest MongoDB driver and strategies including using PHP Composer...
<?php
require 'vendor/autoload.php';
$client = new MongoDB\Client('mongodb://johndoe:mypassword#localhost:27017');
$collection = $client->ensemble->col1;
$cursor = $collection->aggregate(
array(
array( '$match' => array( '_id' => '5db8683c877c34001559f192' ) ),
array(
'$lookup' => array(
'from' => 'col2',
'localField' => 'productEnsembleId',
'foreignField' => 'id',
'as' => 'col2_data'
)
)
)
);
foreach($cursor as $document) {
print_r($document);
}
?>
PHP Results:
MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[_id] => 5db8683c877c34001559f192
[id] => 1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396
[userId] => DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000
[productEnsembleId] => 8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166
[date] => 2019/11/01
[status] => En cours
[col2_data] => MongoDB\Model\BSONArray Object
(
[storage:ArrayObject:private] => Array
(
[0] => MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[_id] => 5da8948e877c34001529a7f2
[id] => 8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166
[name] => ensemble 2
[image] => fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177
[produits] =>
)
)
)
)
)
)

Categories