I am a beginner to Programming; I am stuck while creating an associative array from an existing associative array
<?php
$arr = array(
array(
"question"=>"I get irritated easily.",
"answer"=>"1"
),
array(
"question"=>"I spend time reflecting on things.",
"answer"=>"1"
),
array(
"question"=>"I am quiet around strangers.",
"answer"=>"1"
),
array(
"question"=>"I make people feel at ease.",
"answer"=>"1"
),
array(
"question"=>"I am exacting in my work.",
"answer"=>"1"
),
array(
"question"=>"I often feel blue.",
"answer"=>"3"
),
array(
"question"=>"I am full of ideas.",
"answer"=>"4"
)
);
$answer_array = array();
foreach( $arr as $questions ) {
$answer_array['text']=$questions['answer'];
}
print_r( $answer_array );
?>
I want the $answer_array in the following format:
$answer_array("text"=>"1 , 1 , 1 , 1 , 1 ,3 , 4")
But I am not getting the correct answer as it displays in the following manner:
Array
(
[text] => 4
)
This is because it overwrites all the other values while iterating and only stores the last value. I need to store all the value as I have mentioned above. Kindly suggest where am I going wrong.
You can try to concat the values by changing
$answer_array['text']=$questions['answer'];
to
if(isset($answer_array['text'])){
$answer_array['text'] .= ', '. $questions['answer'] ;
} else {
$answer_array['text'] = $questions['answer'];
}
You could try using array_map to get the answers to every question.
Then you could use implode to join the strings by a delimiter, in this case a ",":
$answer_array = array(
// Implode joins the strings
'text'=>implode(
// Replace this comma by another delimiter if you like
',',
// Array_map applies a function to every element in a array
array_map(
// Define a function that gets the answer to each question
fn($arr)=>$arr["answer"],
$arr
)
)
);
print_r( $answer_array );
Attempt This Online
You can use array_column function
// Enter your code here, enjoy!
$arr = array(
array(
"question"=>"I get irritated easily.",
"answer"=>"1"
),
array(
"question"=>"I spend time reflecting on things.",
"answer"=>"1"
),
array(
"question"=>"I am quiet around strangers.",
"answer"=>"1"
),
array(
"question"=>"I make people feel at ease.",
"answer"=>"1"
),
array(
"question"=>"I am exacting in my work.",
"answer"=>"1"
),
array(
"question"=>"I often feel blue.",
"answer"=>"3"
),
array(
"question"=>"I am full of ideas.",
"answer"=>"4"
)
);
print_r(array_column($arr, 'answer'));
https://onlinephp.io/c/51126
Related
I having an issue merging arrays. I have 3 arrays that show particular data. I need a way to search through all three arrays and if the record matches the date I need to store it in a new custom array.
I have 3 arrays that need to merge them using the date
The arrays are as follows.
// ARRAY 1
$transactions = array(
array(
"date"=>"2021-03-01",
"trans_count"=>100,
"trans_amount"=>5300
),
array(
"date"=>"2021-03-02",
"trans_count"=>95,
"trans_amount"=>5035
),
array(
"date"=>"2021-03-03",
"trans_count"=>105,
"trans_amount"=>5565
)
);
// ARRAY 2
$overdrafts = array(
array(
"date"=>"2021-03-01",
"od_amount"=>500
),
array(
"date"=>"2021-03-02",
"od_amount"=>1000
),
);
// ARRAY 3
$payouts= array(
array(
"date"=>"2021-03-02",
"amount"=>2300
)
);
I tried to write a function but I got stuck. The end goal is to collect all records from all 3 arrays and coming up with one array.
the expected result should look like this.
$merged_arr = array(
array(
"date"=>"2021-03-01",
"type"=>"transactions",
"trans_count"=>100,
"trans_amount"=>5300
),
array(
"date"=>"2021-03-01",
"type"=>"overdrafts",
"od_amount"=>500,
),
array(
"date"=>"2021-03-02",
"type"=>"transactions",
"trans_count"=>95,
"trans_amount"=>5035
),
array(
"date"=>"2021-03-02",
"type"=>"overdrafts",
"od_amount"=>1000
),
array(
"date"=>"2021-03-02",
"type"=>"payout",
"od_amount"=>2300
),
);
Not 100% sure of how to add the type for each of the different types automatically in a nice way, I'd suggest just adding the types directly on the initial arrays, or looping through each before merging them together.
As for the merging and sorting it's pretty easy and can be done with built-in functionality.
$merged_arr = array_merge($transactions, $overdrafts, $payouts);
usort($merged_arr, function ($left, $right) {
return new DateTime($left['date']) <=> new DateTime($right['date']);
});
// Demo merged array.
print "<pre>";
var_export($merged_arr);
The sort function will work with PHP 7 and up.
I am struggling to get this to work:
$this->Attempt->contain(array('AttemptedQuestion' => array('Question'=>array('Category') ))); //THIS DOESNT WORK
$attempt_to_be_graded = $this->Attempt->findById( $attempt_id );
The resulting data is structured as follows ( no Category ):
array(
Attempt => array(),
AttemptedQuestion => array(
0 => array(
Question => array()
),
1 => array(
Question => array()
),
2 => array(
Question => array()
)
)
)
I think my model associations must be correct because this works fine:
$categories = $this->Attempt->AttemptedQuestion->Question->Category->find('all');
Why is there no Category data in the data returned above?
It appears there is no limit. I cannot prove this, but the problem I was encountering is not caused by hitting a limit and I've seen examples of much deeper associations working correctly.
I did not find similar question
1
$form['level1']['level2'][] = array(
'data' => 'some data',
'type' => 'some type',
);
//etc
2
$form = array(
'level1' => array(
'level2' => array(
array(
'data' => 'some data',
'type' => 'some type',
),
//etc
),
),
);
This is absolutely microoptimizing...
Test 1: 9.0906839370728
Test 2: 8.5538339614868
But the second is more efficient. For example [] is slower as it first has to check for the last index etc...
Also the first has to first check if the array already exists (at every dimension) while in the second case it is clear to PHP that there is a new array.
P.s.: But I don't really know, as the first is less to parse than the second. The parser time I didn't measure... (And I don't suppose that the arrays are now very often recreated?)
2 is more readable than 1.
Also, if you going to play without warning, 1 would be:
$arr = array();
$arr["level1"] = array();
$arr["level1"]["level2"] = array();
//... etc
I want to sort an array by 'hits', but I also want to look for a particular ID and set that as the first iteration, then continue the 'hits' sort.
For example, I have a multidimensional array:
$myarray = array(
array(
"id"=>10,
"hits"=>80
),
array(
"id"=>14,
"hits"=>50
),
array(
"id"=>15,
"hits"=>700
),
array(
"id"=>18,
"hits"=>200
)
);
I want to test whether the id is something particular, i.e. if the id==18 then put it first, then sort by hits. How would I do this, using usort and a custom function?
I think I'm looking for something similar to:
function customsort($a,$b){
if($a["id"]==18){ //or b==18?
return -1;
} else {
return $a["hits"]>$b["hits"];
}
}
usort($myarray,"customsort");
The outcome I would like is for the order to be :
array(
"id"=>18,
"hits"=>200
),
array(
"id"=>14,
"hits"=>50
),
array(
"id"=>10,
"hits"=>80
),
array(
"id"=>15,
"hits"=>700
)
(or if they were labelled ABCD then I need it to be DBAC)
The only thing in your code that might make this NOT work is the return $a["hits"]>$b["hits"];. Your function should return 1/-1 only (not true/false), so change that line to: return $a["hits"]>$b["hits"]?1:-1; and it should work as expected.
Sure enough, it works: http://codepad.org/ItyIa7fB
I have array like this:
array(
'person0' => array( 'name'=>'name0','address'=>'address0' ),
'person1' => array( 'name'=>'name1','address'=>'address1' ),
'person2' => array( 'name'=>'name2','address'=>'address2' )
);
I want to change it like this. (just append a new value in each sub-array)
array(
'person0' => array( 'name'=>'name0','address'=>'address0','type'=>'type0' ),
'person1' => array( 'name'=>'name1','address'=>'address1','type'=>'type1' ),
'person2' => array( 'name'=>'name2','address'=>'address2','type'=>'type2' )
);
Is there any related function in php to perform this action? What is the shortest way to do this. Is it possible without loop?
Thanks
Browse the PHP manual when you wonder if a function exists to do something... it probably does.
http://www.php.net/manual/en/function.array-walk.php
http://php.net/manual/en/function.array-map.php
I'd just write the loop, but you can use those functions if you don't want to.