Put foreach loop result as an key php - php

I'm trying to figure out if its possible to loop a foreach loop in a array, and the loop result should be as the keys of the new array, like this,
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr = array();
foreach($names as $v){
$arr[] = $v;
}
$arr2 = array($arr => $dates);
print_r($arr2);
How do I do that?
Thnaks guys.

There is no need for a foreach loop to achieve that. Just use array_combine:
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr2 = array_combine($names, $dates);
print_r($arr2) Outputs:
Array
(
[joe] => 06/22/1987
[piter] => 05/25/1988
[jack] => 08/26/1990
)
In this situation you don't need to do this, but if you want to know how to use $v as a key for $arr2 in your loop you can just do the assignment in your loop:
$arr2[$v] = ...;

Well, saw #ascii-lime's answer (which is much better) after I typed this up, but just as an alternative I guess...
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr = array();
$i=0;
foreach($names as $v){
$arr[$v] = $dates[$i];
++$i;
}
print_r($arr);

Related

How to match and replace one array values to another array keys if they both start with the same letters?

I have two arrays:
$array_one = array('AA','BB','CC');
And:
$replacement_keys = array
(
""=>null,
"BFC"=>'john',
"ASD"=>'sara',
"CSD"=>'garry'
);
So far I've tried
array_combine and to make a loop and try to search for values but can't really find a solution to match the keys of the second array with the values of the first one and replace it.
My goal is to make a final output:
$new_array = array
(
''=>null,
'BB' => 'john',
'AA' => 'sara',
'CC' => 'garry'
);
In other words to find a matching first letter and than replace the key with the value of the first array.
Any and all help will be highly appreciated.
Here is a solution keeping both $replacement_keys and $array_one intact
$tempArray = array_map(function($value){return substr($value,0,1);}, $array_one);
//we will get an array with only the first characters
$new_array = [];
foreach($replacement_keys as $key => $replacement_key) {
$index = array_search(substr($key, 0, 1), $tempArray);
if ($index !== false) {
$new_array[$array_one[$index]] = $replacement_key;
} else {
$new_array[$key] = $replacement_key;
}
}
Here is a link https://3v4l.org/fuHSu
You can approach like this by using foreach with in_array
$a1 = array('AA','BB','CC');
$a2 = array(""=>null,"BFC"=>'john',"ASD"=>'sara',"CSD"=>'garry');
$r = [];
foreach($a2 as $k => $v){
$split = str_split($k)[0];
$split .= $split;
in_array($split, $a1) ? ($r[$split] = $v) : ($r[$k] = $v);
}
Working example :- https://3v4l.org/ffRWY

How to combine multidimensional array

How to combine multidimension array
<?php
$array[0] = [1=>[2=>[4=>[20=>""]]]];
$array[1] = [1=>[2=>[5=>[21=>""]]]];
$array[2] = [1=>[2=>[5=>[22=>""]]]];
$array[3] = [1=>[2=>[5=>[23=>""]]]];
$array[4] = [1=>[2=>[5=>[25=>""]]]];
$array[5] = [3=>[9=>[12=>[33=>""]]]];
$array[6] = [3=>[9=>[12=>[34=>""]]]];
$array[7] = [3=>[9=>[12=>[38=>""]]]];
?>
how to convert to be like:
$arrays = [1=>[2=>[4=>[20=>""],5=>[21=>"",22=>"",25=>""]]],[3=> [9 => [12 => [33 => "",38 => ""]]]]];
I am tried using array_merge :
$arrays = [];
foreach ($array as $val)
{
$arrays = array_merge($arrays,$val);
}
but the result always the first dimension make increment by that self
I already tried some func(like $arrays = $arrays+$val,array_push etc
) since 2 month ago I thought use array_merge is fine but the issue is make increment by that self so I am still not found the solution, I was also search on google and still no found about this.
Use one of the built-in array functions array_merge_recursive or array_replace_recursive. The code looks like:
$arrays = [];
foreach ($array as $val)
{
$arrays = array_replace_recursive($arrays,$val);
}
http://php.net/manual/en/function.array-merge-recursive.php

Unique php multidimensional array and sort by occurrence

I have a PHP multiD array like:-
$a = array($arrayA, $arrayB, $arrayA, $arrayC, $arrayC, $arrayA...........)
how can I get a resulting array which have distinct elements from this array and sorted with the more occurrence first like:-
array( $arrayA, $arrayB, $arrayC)
because array $arrayA was 3 times in first array so it comes first in resulting array.
I have tried :-
$newArray = array();
$count = count($a);
$i = 0;
foreach ($a as $el) {
if (!in_array($el, $newArray)) {
$newArray[$i] = $el;
$i++;
}else{
$oldKey = array_search($el, $newArray);
$newArray[$oldKey+$count] = $el;
unset($newArray[$oldKey]);
}
}
krsort($newArray);
This is perfectly working but this is very lengthy process because my array has thousands of elements. Thanks in advance for your help.
Try like this :-
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Like #saravanan answer but result sorted:-
<?php
$input = [['b'],['a'],['b'],['c'],['a'],['a'],['b'],['a']];
$result = array_count_values( array_map("serialize", $input));
arsort($result,SORT_NUMERIC);
$result = array_map("unserialize",array_keys($result));
print_r($result);

Pushing an Array element into an existing multidimensional array in codeigniter

I have a query in codeigniter like this
$query_tutors = $this->db->get_where("tutor_info", array('tutor_id' => $tutor_id));
I have also other array elements that I want to pass in the query which depends on some conditions.
So how do I push other multidimensional array elements to the existing array so I can pass the variable as a whole in the query?
array_push is not working in this case.
$array = array();
$array = array("tutor_id" => $tutor_id);
$array = array("online" => $online); // want to merge this to the 1st array.
$query_tutors = $this->db->get_where("tutor_info", $array);
First you're doing it wrong.
$array = array();
$array = array("tutor_id" => $tutor_id);
You're recreating the array again, which will delete it from the memory. Either you have to use
$array['tutor_id'] = $tutor_id;
$array["online"] = $online;
or
$array = array('tutor_id' => $tutor_id, 'online' => $online);
or if you want to merge two arrays
$array = array_merge(array('tutor_id' => $tutor_id), array('tutor_id' => $tutor_id));
Your initial code
$array = [];
$array = ["tutor_id" => $tutor_id];
Now, if you want to add conditional merge, simply follow,
if($condition)
{
$array = array_merge($array, ["online" => $online]);
}
If $condition == true You final array will be,
$array = ['tutor_id' => $tutor_id, 'online' => $online];
You are almost there, just need to read a little bit more about associative arrays.
Solution:
$array = array();
$array["tutor_id"] = $tutor_id;
$array["online"] = $online;
$query_tutors = $this->db->get_where("tutor_info", $array);
This way your $array will have all indexes which you want.
You can do something like this:
$array = array();
if (!empty($tutor_id))
{
$array["tutor_id"] = $tutor_id;
}
if (!empty($online))
{
$array["online"] = $online;
}
$query_tutors = $this->db->get_where("tutor_info", $array);

Php - how to store tuples of 3 elements in an array?

I need to store three string values at each iteration of a loop, e.g.
$myArray = array();
foreach (..) {
$myArray[] = // I need to store as a single row or tuple three strings
}
foreach ($myArray as $arrayTuple)
// Do something with $arrayTuple.firstString, $arrayTuple.secondString and $arrayTuple.thirdString
I can't seem to understand how to do this with an associative array.
If I understand correctly then you want like this
$myArray = array();
foreach (..) {
$myArray[] = array("one","two","three");
}
This should helps you, if I understand you correctly:
foreach ($array as $key => $val) {
$myArray[$key] = $val;
}
You can use array_push()
For example:
$myArray = array();
array_push($myArray, "one","two","three");
Or
$myArray = array();
array_push($myArray, "one:two:three");

Categories