Comparing two arrays depending on the order of id - php

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"
]

Related

laravel compare from array in controller with if lease condition

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 .');
}

Foreach does not return all values

I have a foreach but it only returns the last value and not all the values, what is the problem?
my array
array:1 [▼
"ciudad" => array:15 [▼
0 => "Piura"
1 => "10"
2 => "0"
3 => "Lima"
4 => "20"
5 => "0"
6 => "Pisco"
7 => "30"
8 => "0"
9 => "Arequipa"
10 => "40"
11 => "0"
12 => "Loreto"
13 => "50"
14 => "0"
]
]
My code:
public function updateciudadpreciosdelivery(Request $request)
{
$data = $request->except(['_token', 'restaurant_id']);
$i = 0;
$result = [];
foreach ($data as $day => $times) {
$day_result = [];
foreach ($times as $key => $time) {
if ($key % 3 == 0) {
$day_result["open"] = $time;
}
elseif ($key % 2 == 0) {
$day_result["cod"] = $time;
}
else {
$day_result["close"] = $time;
}
}
$result[$day][] = $day_result;
}
// Fetches The Restaurant
$restaurant = Restaurant::where('id', $request->restaurant_id)->first();
// Enters The Data
if (empty($result)) {
$restaurant->deliveryciudadprecios = null;
}
else {
$restaurant->deliveryciudadprecios = json_encode($result);
}
$restaurant->delivery_charge_type = 'XCIUDAD';
// Saves the Data to Database
$restaurant->save();
return redirect()->back()->with(['success' => 'Las ciudades se guardaron correctamente']);
}
Currently it only returns the last value
"{"ciudad":[{"open":"Loreto","close":"50","cod":"0"}]}"
I need you to return the following (example)
{"ciudad":[{"open" :"Piura","close" :"10","cod" :"0"},{"open" :"Lima","close" :"20","cod" :"0"},{"open" :"Pisco","close" :"30","cod" :"0"},{"open" :"Arequipa","close" :"40","cod" :"0"},{"open" :"Loreto","close" :"50","cod" :"0"}]}
If it is not clear I will try to improve it
If we consider your data won't change, and you have 3 entries to get, you can use array_chunk:
$result = [];
foreach ($data as $day => $times) {
$timesChunked = array_chunk($times, 3);
foreach ($timesChunked as $time) {
$result[$day] []= [
'open' => $time[0],
'close' => $time[1],
'code' => $time[2],
];
}
}
But your problem was logical, you don't change the key in your loop, of course your array will have only the last elements. Reread your code, and try to understand why.

Returning elements from an array nest based on criteria

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;
}
}

Merge value of 1 array to another array where keys are the same

I have 2 arrays and I want to push a value from one array to another where keys values equal each other.
1st array
$retail_rates=[
{
"supplier": "ALAMO",
"rateTotalAmount": 293.44,
"estimatedTotalAmount": 495.34, //i want to add this AS retailTotalAmount
"numDays": 9 // i want to add this
},
{
"supplier": "HERTZ",
"rateTotalAmount": 317.16,
"estimatedTotalAmount": 537.43,
"numDays": 9
}
]
2nd array
$net_rates =[
{
"reference_number": "COMPEKYP7537400-2401",
"supplier": "HERTZ",
"rateTotalAmount": 203.01,
"estimatedTotalAmount": 291.21
},
{
"reference_number": "REF_ID:867692955",
"supplier": "ALAMO",
"rateTotalAmount": 147,
"estimatedTotalAmount": 225.58
}
]
What I want to end up with
$final_array=[
{
"reference_number": "COMPEKYP7537400-2401",
"supplier": "HERTZ",
"rateTotalAmount": 203.01,
"estimatedTotalAmount": 291.21,
"retailTotalAmount": 537.43,
"numDays": 9
},
{
"reference_number": "REF_ID:867692955",
"supplier": "ALAMO",
"rateTotalAmount": 147,
"estimatedTotalAmount": 225.58,
"retailTotalAmount": 495.34
"numDays": 9
}
// and so on all the way through
]
I have tried several loops but can't seem to fill it properly. Please help if you can
Iterate one time over the first array and create an assoc array with the supplier as the key. Then iterate over the second array and append it to the first one.
$final_array = [];
foreach ($retail_array as $item) {
$final_array[$item['supplier']] = $item;
}
foreach ($net_array as $item) {
if (isset($final_array[$item['supplier']])) {
$final_array[$item['supplier']] = $item + $final_array[$item['supplier']];
} else {
$final_array[$item['supplier']] = $item;
}
}
Try this
$result = [];
foreach ($net_rates as $net_key => $net_rate) {
foreach ($retail_rates as $retail_key => $retail_rate) {
if ($retail_rate['supplier'] != $net_rate['supplier']) {
continue;
}
$data = $net_rate;
$data['retailTotalAmount'] = $retail_rate['estimatedTotalAmount'];
$data['numDays'] = $retail_rate['numDays'];
$result[] = $data;
unset($retail_rates[$retail_key]);
unset($net_rates[$net_key]);
break;
}
}
$result = array_merge($result, $retail_rates);
$result = array_merge($result, $net_rates);
dd($result);
result is
array:2 [▼
1 => array:6 [▼
"reference_number" => "COMPEKYP7537400-2401"
"supplier" => "HERTZ"
"rateTotalAmount" => 203.01
"estimatedTotalAmount" => 291.21
"retailTotalAmount" => 537.43
"numDays" => 9
]
0 => array:6 [▼
"reference_number" => "REF_ID:867692955"
"supplier" => "ALAMO"
"rateTotalAmount" => 147
"estimatedTotalAmount" => 225.58
"retailTotalAmount" => 495.34
"numDays" => 9
]
]

How to save it in database

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();
}

Categories