Including variables in keys and values in PHP - php

Is there any way to shorten this array
array = [ 'student1' => 'id1', 'student2' => 'id2',];
to something like this?
array = ['student' . $n => 'id' . $n];
I will appreciate if you give me words to search!
Edit:
Sorry for the poor explanation. I wanted to do something like this:
$array = ['student'.$n => 'id'.$n];
echo($array['student1']); //id1

Loop the number of students you need and build the array with array_merge.
$students = 10;
$arr = [];
for($i = 1; $i<=$students; $i++){
$arr = array_merge($arr, ['student' . $i => 'id' . $i]);
}
var_dump($arr);
output:
array(10) {
["student1"]=>
string(3) "id1"
["student2"]=>
string(3) "id2"
["student3"]=>
string(3) "id3"
["student4"]=>
string(3) "id4"
["student5"]=>
string(3) "id5"
["student6"]=>
string(3) "id6"
["student7"]=>
string(3) "id7"
["student8"]=>
string(3) "id8"
["student9"]=>
string(3) "id9"
["student10"]=>
string(4) "id10"
}

Related

How can I flatten a Multidimensional array into a string?

Ive researched this but im coming up blank, Im generating an array of tests from a database like so:
$descriptions = array();
foreach ($tests as $value) {
array_push($descriptions, ['name' => $value['name']]);
}
I'm getting the desired out put but i'm getting a Multidimensional array of an array with '[64]' arrays inside '$descriptions', I need to convert this array so I get the following output:
'name' => $value1, 'name' => $value2, etc etc for all results,
I've tried implode, array_merge etc but the closest I've got is a flat array with only my last test: [name] => Zika can anyone point me in the right direction? cheers
You can't have duplicate array keys. But you can pass an array in like so:
<?php
$descriptions = array();
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions[] = array('name' => $value);
}
var_dump($descriptions);
Which gives you :
array(6) { [0]=> array(1) { ["name"]=> string(4) "Zika" } [1]=> array(1) { ["name"]=> string(4) "SARS" } [2]=> array(1) { ["name"]=> string(4) "AIDS" } [3]=> array(1) { ["name"]=> string(15) "Mad Cow Disease" } [4]=> array(1) { ["name"]=> string(8) "Bird Flu" } [5]=> array(1) { ["name"]=> string(16) "Zombie Infection" } }
So you could foreach ($descriptions as $desc) and echo $desc['name']';
Have a look here: https://3v4l.org/pWSC6
If you just want a string, try this:
<?php
$descriptions = '';
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions .= 'name => '.$value.', ';
}
$descriptions = substr($descriptions, 0, -2); // lose the last comma
echo $descriptions;
Which will output:
name => Zika, name => SARS, name => AIDS, name => Mad Cow Disease, name => Bird Flu, name => Zombie Infection
See it here https://3v4l.org/OFGF4

Combine multiple form array into 1 array

["trnx_date"]=>
array(2) {
[0]=>
string(10) "2017-01-10"
[1]=>
string(10) "2017-01-10"
}
["curr_from"]=>
array(2) {
[0]=>
string(3) "USD"
[1]=>
string(3) "PHP"
}
["curr_from_amt"]=>
array(2) {
[0]=>
string(8) "4,000.00"
[1]=>
string(8) "3,000.00"
}
["curr_to"]=>
array(2) {
[0]=>
string(3) "GBP"
[1]=>
string(3) "SAR"
}
["curr_to_amt"]=>
array(2) {
[0]=>
string(8) "3,000.00"
[1]=>
string(8) "2,000.00"
}
["amount"]=>
array(2) {
[0]=>
string(8) "7,000.00"
[1]=>
string(8) "5,000.00"
}
I have the above array which was being submitted. This input was in sets of multiple field which was generated by dynamic table row. How can I group this into 1 (one) array so that I could save in the database? Like this:
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "USD",
'curr_from_amt' => "4,000.00",
'curr_to' => "GBP",
'curr_to_amt' => "3,000.00",
'amount' => "7,000.00"
),
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "PHP",
'curr_from_amt' => "3,000.00",
'curr_to' => "SAR",
'curr_to_amt' => "2,000.00",
'amount' => "5,000.00"
),
All of the above we being populated like this:
$trnx_date = $this->input->post('trnx_date');
$curr_from = $this->input->post('curr_from');
$curr_from_amt = $this->input->post('curr_from_amt');
$curr_to = $this->input->post('curr_to');
$curr_to_amt = $this->input->post('curr_to_amt');
$amount = $this->input->post('amount');
Assuming all the sub-arrays have the same length, you can use a simple for loop that iterates over the index of one of them, and use that to access each of the sub-arrays at that index. Then combine all of them into the associative array for each customer.
$result = array();
$keys = array_keys($array);
$len = count($array[$keys[0]]); // Get the length of one of the sub-arrays
for ($i = 0; $i < $len; $i++) {
$new = array();
foreach ($keys as $k) {
$new[$k] = $array[$k][$i];
}
$result[] = $new;
}
$arr = array(
'trnx_date' => array('2017-01-10', '2017-01-10'),
'curr_from' => array('USD', 'PHP'),
'curr_from_amt' => array('4,000.00', '3,000.00'),
'curr_to' => array('GBP', 'SAR'),
'curr_to_amt' => array('3,000.00', '2,000.00'),
'amount' => array('7,000.00', '5,000.00')
);
$arr_out = array();
$arr_keys = array_keys($arr);
for($i = 0; $i < count($arr[$arr_keys[0]]); $i++) {
$new_arr = array();
foreach($arr_keys as $key => $value) {
$new_arr[$value] = $arr[$value][$i];
}
$arr_out[] = $new_arr;
}
var_dump($arr_out);
Hope it helps!
How about this?
// assume $arr is your original data array
$keys = array_keys($arr);
$result = array();
foreach($keys as $key) {
$vals = $arr[$key];
foreach($vals as $i =>$val) {
if (!is_array($result[$i]) {
$result[$i] = array();
}
$result[$i][$key] = $val;
}
}
var_dump($result);
EDIT: added array check for $result[$i]

Building an array in PHP with Codeigniter

I'm trying to build an array in Codeigniter 3, but I cant seem to structure it properly.
I have 2 tables that I basically need to combine; questions and their associated answers.
SO, basically I need a multidimensional array, each inner array is to contain the question data along with its associated answer data.
This is what I'm doing at the moment:
$question_array = array();
foreach($course_object->result() as $question){
$question_array[] = array (
'question_id' => $question->question_id,
'question' => $question->question,
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$question_array[]['answer'] = $answer->answer;
$question_array[]['result'] = $answer->result;
}
}
return $question_array;
But that outputs each question as an array on its own, as well as each answer, i need to combine them somehow. This is what I'm getting:
array(2) {
["question_id"]=>
string(3) "548"
["question"]=>
string(29) "Who enforces fire safety law?"
}
array(1) {
["answer"]=>
string(11) "The Manager"
}
array(1) {
["result"]=>
string(1) "0"
}
array(1) {
["answer"]=>
string(18) "The Fire Authority"
}
array(1) {
["result"]=>
string(1) "1"
}
and this is what i need:
array(2) {
["question_id"]=>
string(3) "548"
["question"]=>
string(29) "Who enforces fire safety law?"
["answer"]=>
string(11) "The Manager"
["result"]=>
string(1) "0"
["answer"]=>
string(18) "The Fire Authority"
["result"]=>
string(1) "1"
}
I've tried things like array_push but I cant seem to get it to work?
Any ideas what I can try?
The easiest way to do it is to create a new array with what you need, and append it to the $question_array, like this. You'll need a new subarray for the answers, because you can't have duplicate keys in an array.
foreach($course_object->result() as $question){
$q_array = array (
'question_id' => $question->question_id,
'question' => $question->question,
'answers' => array()
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$q_array['answers'][] = array(
'answer' => $answer->answer,
'result' =>$answer->result
);
}
$question_array[] = $q_array;
}
I think this should work.
$question_array = array();
$i = 0;
foreach($course_object->result() as $question){
$question_array[$i] = array (
'question_id' => $question->question_id,
'question' => $question->question,
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$question_array[$i]['answer'][] = $answer->answer;
$question_array[$i]['result'][] = $answer->result;
}
$i++;
}
return $question_array;

Php array get all values that are repeating

I have a Php array that have values of times as array values and timestamps as key array is like this:
array(
144454884=>"12:00am", 145454884=>"12:30am", 144474884=>"1:00am", 144454864=>"1:30am", 143354884=>"1:00am", 144654884=>"1:30am", 1444567584=>"2:00am "
);
Timestamp values in above example are not real I wrote an example they are useless anyway unless your timezone matches mine.
Problem:
I need to get "1:00am" and "1:30am" twice I can get repeating values 1 time as shown in answer here:
php return only duplicated entries from an array
I need both repeating values two times with both keys and values being repeated because I need to eliminate those timestamps from week time on my system because of daylight saving a time is repeating and I don't want to show 1:00am at all I just want to show this time as unavailable.
I am not 100% sure what you wanted but this is what I think you need.
Assuming your input array is called $a
$b = array_flip(array_flip($a));
$c = array_diff_key($a, $b);
$b will contain an array of unique values.
$c will contain the elements that were removed.
Results of $b and $c are as follows:
array(5) {
[144454884] = string(7) "12:00am"
[145454884] = string(7) "12:30am"
[143354884] = string(6) "1:00am"
[144654884] = string(6) "1:30am"
[1444567584] = string(7) "2:00am "
}
array(2) {
[144474884] = string(6) "1:00am"
[144454864] = string(6) "1:30am"
}
This code works :
<?php
$array_new = [];
$array_tmp = [];
$array = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');
//loop trough all elements in array and for ever element create key
//For "world" key is "world"
//For "World" key is "world"
//For "WORLD" key is "world"
//So all this cases have same key and differenet representation eg. "world" => ["world","World","WORLD"]
foreach($array as $k => $v){
$index = strtolower($v);
$array_tmp[$index][] = $v;
}
//loop trough new array with new keys and if there are more than one element(> 1) for some key, all of his representations put in new array
foreach($array_tmp as $k => $v){
if(count($v) > 1){
foreach($v as $k2 => $v2){
$array_new[] = $v2;
}
}
}
echo '<pre>';
print_r($array_new);
echo '<pre>';
A possible solution keeping the key information (I will assign the intermediate results to their own variables otherwise it can be confusing to read)
$array = array(
143354883 => "1:00am",
144454884 => "12:00am",
145454884 => "12:30am",
144474884 => "1:00am",
144454864 => "1:30am",
143354884 => "1:00am",
144654884 => "1:30am",
1444567584 => "2:00am ",
0 => 4,
1 => 4,
2 => 4,
3 => "Test",
4 => "TEST",
5 => "test "
);
// Used this array_iunique function: http://stackoverflow.com/questions/2276349/case-insensitive-array-unique
function array_iunique($array) {
return array_intersect_key(
$array,
array_unique(array_map("StrToLower",$array))
);
}
$unique = array_iunique($array);
// Then get the difference by key, that will give you all the duplicate values:
$diff_key = array_diff_key($array, $unique);
// Now we have to find the values that are in the $diff_key and the $unique because we also want to have those:
$correspondingValues = array_uintersect($unique, $diff_key, "strcasecmp");
// Then we have to combine the $duplicate values with the $diff_key and preserve the keys:
$result = array_replace($correspondingValues, $diff_key);
var_dump($result);
Will result in:
array(10) {
[143354883]=>
string(6) "1:00am"
[144454864]=>
string(6) "1:30am"
[0]=>
int(4)
[3]=>
string(4) "Test"
[144474884]=>
string(6) "1:00am"
[143354884]=>
string(6) "1:00am"
[144654884]=>
string(6) "1:30am"
[1]=>
int(4)
[2]=>
int(4)
[4]=>
string(4) "TEST"
}

How to change name of keys of a multidimensional array

I have two arrays one of them contain a new key name
$assoc = ['name', 'lastname', 'pesel'];
and second look this
$inputs = ['John', 'Don', '987987', 'Mike', 'Evans', '89779' ];
Array $assoc is the new key name, and I would like to change [0],[1] to ['name'] etc
array(2) {
['person'] =>
array(3) {
['name'] => string(4) "John"
['lastname'] => string(3) "Don"
['pesel'] => string(6) "987987"
}
['person'] =>
array(3) {
['name'] => string(4) "Mike"
['lastname'] => string(5) "Evans"
['pesel'] => string(5) "89779"
}
}
Thanks for your help
It's pretty simple:
$new_array = array();
foreach(array_chunk($inputs, 3) as $person) {
$new_array[] = array_combine($assoc, $person);
}
<?php
$assoc=Array("name", "lastname", "pesel");
$inputs=Array('John', 'Don', '987987', 'Mike', 'Evans', '89779' );
$resultant_array=Array();
for($i=0; $i<count($inputs); $i+=count($assoc)){
//echo $i."\n\n";
for($j=0; $j<count($assoc); $j++){
$b2g[$assoc[$j]]=$inputs[$i+$j];
}
$resultant_array[]=$b2g;
}
print_r($resultant_array);
It is a more lengthy and general purpose use.. I actually have used much recurssions..

Categories