Edit :
i Want a structure like this
'categories' => [
[
'name' => "science" ,
'questions' => [
[
'question' => 'C1_Q2',
'answer' => 'C1_A2',
],
[
'question' => 'C1_Q3',
'answer' => 'C1_A3',
]
]
]
but with help of loop
I am trying to create a questionnaire in which 3 steps need to be done
Create 3 arrays
1.categories - 2d -- like category["science"]["questions"]
2.questions
3.answers
step 1. add 10 questions in question array and add 10 answers in answer arrays
step 2.first 5 question of question array should be inserted to categories["science"]["questions"] and 5 answers to categories["science"]
["answers"]
I created Question and answer array and added 10 , 10 elements in it . but didnt succeed to add its elements as per step2 . I tried few logic
$Category=array();
$Q=array();
$A=array();
for($i=1;$i<=10;$i++)
{
$Q[] = "Question post".$i;
$A[] = "Answer post".$i;
//if($i==5)
//{
// array_push($Category,$Q[i]);
// break;
//} ---logic not working
}
//array first 5 Questions to category array
/*
for($i=1;$i<=5;$i++)
{
//$Category[]=$Q[i];
array_push($Category,$Q[i]);
}
*/ -- not working
print_r($Category);
Any suggestion or help would be appreciated
Try this:
$questions = [];
$answers = [];
for($i=1; $i <= 10; $i++) {
$questions[] = 'Question post' . $i;
$answers[] = 'Answer post' . $i;
}
$categories = ['science', 'something', 'else'];
$result = [];
foreach ($questions as $index => $question) {
if ($index % 5 != 0 || $index == 0) {
$category = current($categories);
} else {
$category = next($categories);
}
$result[$category][] = ['question' => $question, 'answer' => $answers[$index]];
}
var_dump($result);
Related
This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 7 months ago.
I have 2 xPath requests :
$medias = $xpath->query("//strong//a[contains(#class, 'no')]");
$links = $xpath->query("//strong//a[contains(#class, 'no')]/#href");
My goal is to have only one array that contains something like this :
0 => array:1 [▼
"title" => "A besúgó"
"link" => "xyz"
]
I tried this
$i=0;
foreach($medias as $media)
{
$tab[]['titre'] = $media->textContent;
$i++;
}
$i=0;
foreach($medias as $media)
{
$tab[]['lien'] = $media->textContent;
$i++;
}
dd($tab);
But it's ugly and it does not work. Can you help ?
It's hard to understand what you are trying to achieve, but from what I can tell it is this.
$tab = [];
for ($i = 0; $i < count( $medias ); $i++ ) {
$tab[] = [ 'titre' => $medias[$i], 'lien' => $links[$i] ];
}
you may just use array_merge() function to merging more than 1 arrays
array_merge(array1, array2, array3, ...)
I have a already defined array, containing values just like the one below:
$arr = ['a','b','c'];
How could one add the following using PHP?
$arr = [
'a' => 10,
'b' => 5,
'c' => 21
]
I have tried:
$arr['a'] = 10 but it throws the error: Undefined index: a
I am surely that I do a stupid mistake.. could someone open my eyes?
Full code below:
$finishes = []; //define array to hold finish types
foreach ($projectstages as $stage) {
if ($stage->finish_type) {
if(!in_array($stage->finish_type, $finishes)){
array_push($finishes, $stage->finish_type);
}
}
}
foreach ($projectunits as $unit) {
$data[$i] = [
'id' => $unit->id,
'project_name' => $unit->project_name,
'block_title' => $unit->block_title,
'unit' => $unit->unit,
'core' => $unit->core,
'floor' => $unit->floor,
'unit_type' => $unit->unit_type,
'tenure_type' => $unit->tenure_type,
'floors' => $unit->unit_floors,
'weelchair' => $unit->weelchair,
'dual_aspect' => $unit->dual_aspect
];
$st = array();
$bs = '';
foreach ($projectstages as $stage) {
$projectmeasure = ProjectMeasure::select('measure')
->where('project_id',$this->projectId)
->where('build_stage_id', $stage->id)
->where('unit_id', $unit->id)
->where('block_id', $unit->block_id)
->where('build_stage_type_id', $stage->build_stage_type_id)
->first();
$st += [
'BST-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure : '0')
];
if (($stage->is_square_meter == 0) && ($stage->is_draft == 0)) {
$height = ($stage->height_override == 0 ? $unit->gross_floor_height : $stage->height_override); //08.14.20: override default height if build stage type has it's own custom height
$st += [
'BST-sqm-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure * $height: '0')
];
if ($stage->finish_type) {
$finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure * $height: '0') * ($stage->both_side ? 2 : 1); //error is thrown at this line
}
} else {
if ($stage->finish_type) {
$finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure : '0');
}
}
}
$data[$i] = array_merge($data[$i], $st);
$data[$i] = array_merge($data[$i], $finishes[$stage->finish_type]);
$i++;
}
The above code is used as is and the array $finishes is the one from the first example, called $arr
You're using += in your real code instead of =. That tries to do maths to add to an existing value, whereas = can just assign a new index with that value if it doesn't exist.
+= can't do maths to add a number to nothing. You need to check first if the index exists yet. If it doesn't exist, then assign it with an initial value. If it already exists with a value, then you can add the new value to the existing value.
If you want to convert the array of strings to a collection of keys (elements) and values (integers), you can try the following:
$arr = ['a','b','c'];
$newVals = [10, 5, 21];
function convertArr($arr, $newVals){
if(count($arr) == count($newVals)){
$len = count($arr);
for($i = 0; $i < $len; $i++){
$temp = $arr[$i];
$arr[$temp] = $newVals[$i];
unset($arr[$i]);
}
}
return $arr;
}
print_r(convertArr($arr, $newVals));
Output:
Array ( [a] => 10 [b] => 5 [c] => 21 )
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Name Number
1 Benjoe 001
2 Benjoe 002
3 Benjoe 001
Given the data, how can I determine that I found duplicate data (Row 1 and 3) using foreach? I have playing with this code right now.
Update: 02/14/2020 - I came up with this algorithm. I've added a flag to determine If I found a duplicate.
$results = [
['name' => 'Benjoe', 'number' => '001'],
['name' => 'Benjoe', 'number' => '002'],
['name' => 'Benjoe', 'number' => '001'],
];
foreach($results as $log) {
if($name == $log->vlg_full_name && $number == $log->vlg_contact_number) {
$isDuplicateNameAndNo = 1;
} else {
$isDuplicateNameAndNo = 0;
break;
}
$name = $log->vlg_full_name;
$number = $log->vlg_contact_number;
}
You can achieve this by a nested loop iterating throug the each element and compating it to the current one.
Try something like that:
<?php
$results = [
['name' => 'Benjoe', 'number' => '001'],
['name' => 'Benjoe', 'number' => '002'],
['name' => 'Benjoe', 'number' => '001'],
];
function compare($log1, $log2, $index1, $index2)
{
return $log1['name'] == $log2['name']
&& $log1['number'] == $log2['number']
&& $index1 != $index2;
}
foreach($results as $index1 => $log1) {
foreach ($results as $index2 => $log2) {
if (compare($log1, $log2, $index1, $index2)) {
echo "Item {$index1} has a duplicate at index {$index2}!<br/>\n";
}
}
}
Here is a link to working example on 3v4l.org
The output for the above will be:
Item 0 has a duplicate at index 2!<br/>
Item 2 has a duplicate at index 0!<br/>
If you don't need to exactly know wich items are duplicate you can simply concatenate the values and put them into an array, and check if the value is already there:
<?php
$results = [
['name' => 'Benjoe', 'number' => '001'],
['name' => 'Benjoe', 'number' => '002'],
['name' => 'Benjoe', 'number' => '001'],
];
$temp = [];
foreach($results as $index => $log) {
$val = $log['name'] . '_' . $log['number'];
if (in_array($val, $temp)) {
echo "Duplicate found at index {$index}<br/>\n";
} else {
$temp[] = $val;
}
}
Output:
Duplicate found at index 2<br/>
Working example on 3v4l.org
If you get your $results from database, another approach would be grouping the query by the requried columns and adding the count(*) field to gind out how many records exists.
This question already has answers here:
How to GROUP BY and SUM PHP Array? [duplicate]
(2 answers)
Closed 9 months ago.
I want to sum subarray values and group by a subarray value but I am getting error: 'Undefined index: EEReg'.
The array is as follows.
and the current code is;
$total_balances = array();
foreach ($balances as $balance) {
foreach ($balance as $key => $value) {
if ($key == 'MemberNumber' || $key == 'Portfolio') {
continue;
} else {
$total_balances[$balance['Portfolio']][$key] += $value;
}
}
}
I expect the result to be;
$total_balances = [
"Aggressive" => [
"EEReg" => "Sum of EEReg where Portfolio is Aggressive",
"ERReg" => "Sum of ERReg where Portfolio is Aggressive",
],
"Moderate" => [
"EEReg" => "Sum of EEReg where Portfolio is Moderate",
"ERReg" => "Sum of ERReg where Portfolio is Moderate",
]
]
You need to use foreach only once and also you need to define the keys in $total_balance array before using them. Please see below code
$total_balances = array();
foreach ($balances as $balance) {
if( !isset( $total_balances[$balance['Portfolio']] )) {
$total_balances[$balance['Portfolio']] = array('EEREG' => 0, 'ERREG' => 0);
}
$total_balances[$balance['Portfolio']]['EEREG'] += $balance['EEREG'];
$total_balances[$balance['Portfolio']]['ERREG'] += $balance['ERREG'];
}
My question is how can I search an array built this way? Basically there may be a need to repeat the key and this is what I got so far to maybe solve this. If the price is the same for 2 different items I cannot have 2 keys with the same value.
Please feel free to improve on array layout.
$price_list = array(
1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")
);
Provided there will never be any duplication of the second column, you can do this:
$search = "EA_WTRESRVD"; //value to search for
$price_list = array(
1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")
);
$array = array_column($price_list, 0, 1);
echo $array[$search];
I would suggest that if you have a unique product code (SKU), you should use this to index your array.
$products = [
'EA_WTRESRVD' => [
'name' => '...',
'price' => 9.99,
// ...
],
'EA_WTRESRV' => [
'name' => '...',
'price' => 9.99,
// ...
],
];
Then you can access the price of any product by it's SKU.
$price = $products['EA_WTRESRV']['price'];
Here's one way:
<?php
$price_list = [ 1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")];
$search = "EA_WTRESRV";
foreach ($price_list as $arr) {
if (in_array( $search, $arr )) {
echo $search;
}
}
The foreach iterates over the multidimensional array whose elements are each arrays. Each array is inspected by in_array() for the search term.
However, this is not the only way. If you wish to avoid in_array(), you could also code as follows:
<?php
$price_list = [ 1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")];
$search = "EA_WTRESRV";
$len = strlen($search);
foreach ($price_list as $arr) {
$val = array_values($arr);
foreach($val as $v) {
if ( ( strpos( $v,$search )) !== false) {
if ( strlen($v) == $len) {
echo "$search is in the price list.\n";
}
}
}
}