I'm trying to compare array getting from two different inputs and compare it in controller if both value same then pass TRUE if Not pass FALSE.
I tried below method but I was getting error and error pointing to below code
if ($request->ANSWER[$i] === $request->OPTION[$i])
{
$data->ANSWER_STATUS = "1";
} else {
$data->ANSWER_STATUS = "0";
}
Error Code
Trying to access array offset on value of type null
my array pater looks
"Question" => array:2 [▼
0 => "html full form"
1 => "water formula in science"
]
"ANSWER" => array:2 [▼ //COMPARE
0 => "Hypertext Markup Language"
1 => "h2O"
]
"OPTION" => array:2 [▼ //COMPARE
0 => "Markup Language"
1 => "h2O"
]
Controller
public function Store_Answer(Request $request)
{
$Questioncount= $request->Question;
if ($Questioncount) {
for ($i=0; $i <count($request->Question); $i++) {
$data = New OnlineExminAnswer();
if ($request->ANSWER[$i] === $request->OPTION[$i])
{
$data->ANSWER_STATUS = "1";
} else {
$data->ANSWER_STATUS = "0";
}
$data->question = $request->Question [$i];
$data->save();
}
}
return back()->with('success',' Successfully .');
}
Related
I am trying to save the Home model with its realation ship called Phone that I want to insert unlimited Phones for it . Now I am inserting home without any problem but when it comes to phone I can't insert my 2d array into phone ! Here is my controller :
$validated = $request->all();
if (!$validated) {
return $this->sendError('Validation Error.', $validated->errors());
}
$home = Home::create($validated);
$phones = $request->input('phones');
for ($i =0; $i < count($phones); $i++) {
$insertPhone[$i] = json_decode($phones[$i]);
}
dd($insertPhone);
$home->phones()->createMany($insertPhone);
return new HomeResource($home);
and down there is the dd result of $insertPhone :
array:2 [
0 => {#533
+"value": "123"
+"is_attachment": "true"
}
1 => {#538
+"value": "456"
+"is_attachment": "true"
}
]
createMany expects a multidimensional array with key / value, for example :
$home->phones()->createMany([
[
'number' => '049230323432',
],
[
'number' => '432094249023',
],
]);
So you should do like :
$phones = $request->input('phones');
$insertPhone = [];
foreach ($phones as $phone) {
$insertPhone []= [
'number' => $phone,
];
}
I am trying to search an array for an element (in this case 'electronic'), then return the nested value.
The array that I am working with
array:2 [▼
0 => array:2 [▼
"value" => "0241-6230"
"type" => "print"
]
1 => array:2 [▼
"value" => "2339-1623"
"type" => "electronic"
]
]
Below is the code I'm using.
<?php
$this->doi = 'anydoinumber';
$this->client = new Client();
$this->Url = 'https://api.crossref.org/works/:'.$this->doi;
$res = $this->client->get($this->Url);
$decoded_items = json_decode($res->getBody(), true);
if (isset($decoded_items['message']['issn-type'])) {
$this->issn = '';
} else {
// no electronic ISSN given
Log.Alert('No electronic ISSN for :'.$this->Doi);
}
The output I'm expecting
$this->issn = "2339-1623"
You can use laravel collection:
collect($array)->where('type', 'electronic')->first();
And output is:
array:2 [
"value" => "2339-1623"
"type" => "electronic"
]
You could use a simple foreach loop that adds matching elements to a results array
$filtered = [];
foreach($myarr as $i){
if($i['type'] == 'searched type')
$filtered[] = $i;
}
or you can break out of the loop when you encounter first element of given type
foreach($myarr as $i){
if($i['type'] == 'searched type')
return $i; // or $found = $i and then break;
}
PHP way:
$searchingFor = 'electronic';
$filteredArray = array_filter($initialArray, function($v, $k) use ($searchingFor) {
return $searchingFor === $v['type'];
}, ARRAY_FILTER_USE_BOTH);
//var_dump($filteredArray);
Docs.
You Have To user foreach loop
$searchterm = 'electronics';
foreach($nested as $key => $value) {
if($value['type'] == $searchterm) {
return $value['value'];
break;
}
}
I have this code and I want to compare depending of the order of id
this is the code:
foreach ($questions as $question) {
$question_answers = OrderingAnswer::where('question_id', $question->id)
->where('deleted', 0)
->get()
->toArray();
$question_answer = $request->except('_token', 'test_id');
$answers = $question_answer[ $question->id];
foreach ($question_answers as $answer) {
if ($answer === $answers) {
$answer_result[] = 1;
} else {
$answer_result[] = 0;
}
}
if (in_array(0, $answer_result)) {
$question_results[$question->id] = 0;
} else {
$question_results[$question->id] = 1;
}
$answer_result = [];
$results = $question_results;
}
I have tried array_diff, array_intersect but wont work, the result of the dd($answer); is like this
array:5 [▼
"id" => 239
"question_id" => 239
"text" => "something"
"order" => 1
"deleted" => 0
]
and the result of the dd($answers); is this
array:4 [▼
0 => "239"
1 => "240"
2 => "241"
3 => "242"
]
In my database i have column like id,product_id,company_name,service,qty,delivery_cost,delivery_date,order_status etc.
I view i used Jquery and Html and jquery dynamically add more input fields of product_id,service,delivery_cost,qty,delivery_date,order_status on clicking ADD more button.On submiting form i got this in controller on doing dd($allData);
My question is how can i save this data in database
array:8 [▼
"_token" => "gSddIeA11OBV60xU9YiDXn8fmsfkwxlQ85QmDdkQ"
"service" => array:3 [▼
0 => "cement"
1 => "iron"
2 => "steel"
]
"qty" => array:3 [▼
0 => "5"
1 => "44"
2 => "5"
]
"delivery_cost" => array:3 [▼
0 => "5465"
1 => "553"
2 => "554"
]
"delivery_date" => array:3 [▼
0 => "2016-12-16"
1 => "2016-12-08"
2 => "2016-12-17"
]
"order_status" => "Confirm"
"delivery_vehicle" => array:1 [▼
0 => "Self_elivery"
1 => "Self_elivery"
2 => "Self_elivery"
]
]
public function store(Request $request)
{
$allData= $request->all();
dd($allData);
$product = new Order;
}
i try this
public function store(Request $request)
{
$date = $request->get('delivery_date');
$cost = $request->get('delivery_cost');
$service = $request->get('service');//add quotes next to service
foreach($date as $deliveryDate)
{
foreach($cost as $proAmount){
$db = new Order;
$db->delivery_date = $deliveryDate;
$db->amount = $proAmount;
$db->save();
}
}
return"ok";
}
I tried this way but it store same data multiple times may be because of loop inside of loop.I need your help to store this data in database
Using for() should work for you:
$data = $request->all();
for ($i = 0; $i < count($data['delivery_date']); $i++) {
$db = new Order;
$db->delivery_date = $data['delivery_date'][$i];
$db->delivery_cost = $data['delivery_cost'][$i];
....
$db->save();
}
You can try this If you want to use foreach $key will give you the index.
$date = $request->get('delivery_date');
$cost = $request->get('delivery_cost');
$service = $request->get('service');
foreach($date as $key=>$deliveryDate)
{
$db = new Order;
$db->delivery_date = $deliveryDate;
$db->amount = $cost[$key];
$db->save();
}
return"ok";
Hope this help you. Ask if any query
Do bulk insert instead of running new sql query for every insert(if all the request params exist in single table).
$data = [];
foreach ($request->all() as $param => $val) {
if( is_array($val) ) // Ignore string params. i.e. _token, order_status
{
foreach ($val as $key => $value) {
$data[$index][$param] = $value;
$data[$index]['created_at'] = \Carbon\Carbon::now();
$data[$index]['updated_at'] = \Carbon\Carbon::now();
$index++;
}
$index = 0;
}
}
Model::insert($data);
Using foreach() should work for you very easy:
$inputdata = $request->all();
foreach ($inputdata as $key=>$val) {
$dbdata = new Order;
$dbdata ->delivery_date = $data['delivery_date'][$key];
$dbdata ->delivery_cost = $data['delivery_cost'][$key];
....
$dbdata ->save();
}
I make a call to an API by doing the following
$widgets = json_decode(APIHelper::getWidgetsForDashboards($accessToken, $dashboards), true);
The response gives me an array of data which is quite large. I have made an example of what the response for one of the elements is like here
2 => array:23 [▼
"title" => ""
"type" => "smartLabel"
"options" => array:5 [▼
"title" => true
"data" => array:1 [▼
0 => array:3 [▼
"labelName" => "Label"
"labelValues" => array:1 [▼
0 => "Some Name"
]
]
]
]
]
So the Job I am faced with is getting the labelValues. There are some conditions however. I only want the labelValues for objects which have a type of smartLabel. Now I have a working solution which I will show, I just feel like there is a simpler way to achieve this because my current solution involves a lot of nesting. This is what I have done
$titlesArray = array();
foreach($widgets as $widget) {
if ($widget['type'] == 'smartLabel') {
foreach($widget['options'] as $optionKey => $optionValue) {
if($optionKey == 'data') {
foreach($optionValue as $key => $value) {
if($key == 'labelValues') {
foreach($value as $labelKey => $labelValue) {
if($labelKey == 'labelValues') {
foreach($labelValue as $label) {
$titlesArray[] = array(
$label
);
}
}
}
}
}
}
}
}
}
Is there any way to possibly clean this up?
Thanks
Yes you can reduce the nesting by only itterating the arrays with unknown (eg the numerical) keys, and using a negative if clause:
$titlesArray = array();
foreach($widgets as $widget) {
if ($widget['type'] != 'smartLabel') continue;
foreach($widget['options']['data'] as $dataItem) {
foreach($dataItem['lableValues'] as $value) {
$titleArray[]=$value;
}
}
}
You can get rid of two levels by looping over $widget['options']['data'] and $value['labelValues'].
That would also remove two levels of conditional statements.
And then you can also use array_merge() to get all lableValues in one go.
Something like (untested...):
foreach($widgets as $widget) {
if ($widget['type'] === 'smartLabel') {
foreach($widget['options']['data'] as $key => $value) {
$titlesArray = array_merge($titlesArray, $value['labelValues']);
}
}
}
Just for the sake of considering working with Laravel collections you can convert your array and use the nice options the collections give you.
$titlesArray = collect($widgets)->filter(function ($widget) {
return $widget['type'] === 'smartLabel';
})->pluck('options')
->pluck('data')
->flatten(1)
->pluck('labelValues')
->flatten();