Adding Curly Braces on Array of String PHP - php

Im looking for the way to add curly braces {} on my Array of string :
print_r(json_encode($temp));
temp = [{"Red":1,"Blue":2,"Green":2}]
Im creating that values with :
$query_final = (my query);
$query = $this->db->query($query_final)->result_array();
$res = array_count_values(array_column($query, 'status'));
array_push($temp, $res);
print_r(json_encode($temp));
become:
print_r(json_encode($temp));
temp = [{"Red": "1"},{"Idle":"2"},{"Overload":"2"}]
So far i've tried to use implode :
$temp = implode(",", $temp);
print_r(json_encode($temp));
but it just giving the error, is there any way to do the right thing ?

array_count_values() returns a list of the values and the number of times they occur, so just using array_push() will add this entire array as 1 item and give you the results your getting.
Instead, you can add the results one at a time to the $temp array and get the results your after...
$temp = [];
$res = array_count_values(array_column($query, 'status'));
foreach ( $res as $key=>$item ) {
$temp[] = [$key => $item];
}
print_r(json_encode($temp));

Decode your json with json_decode($temp, true);

You can use json_encode on an array to get a JSON. Like so:
$temp = ['Red' => 1,
'Blue' => 2,
'Green' => 2
];
print_r(json_encode($temp)); // {"Red":1,"Blue":2,"Green":2}

Related

Replace array value with more than one values

I have an array like this,
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
I want to find any value with an ">" and replace it with a range().
The result I want is,
array(
1,2,3,4,5,6,7,8,9,10,11,12, '13.1', '13.2', 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
);
My understanding:
if any element of $array has '>' in it,
$separate = explode(">", $that_element);
$range_array = range($separate[0], $separate[1]); //makes an array of 4 to 12.
Now somehow replace '4>12' of with $range_array and get a result like above example.
May be I can find which element has '>' in it using foreach() and rebuild $array again using array_push() and multi level foreach. Looking for a more elegant solution.
You can even do it in a one-liner like this:
$array = array(1,2,3,'4>12','13.1','13.2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,#range(...array_slice(explode(">","$c>$c"),0,2)));},
[]
));
I avoid any if clause by using range() on the array_slice() array I get from exploding "$c>$c" (this will always at least give me a two-element array).
You can find a little demo here: https://rextester.com/DXPTD44420
Edit:
OK, if the array can also contain non-numeric values the strategy needs to be modified: Now I will check for the existence of the separator sign > and will then either merge some cells created by a range() call or simply put the non-numeric element into an array and merge that with the original array:
$array = array(1,2,3,'4>12','13.1','64+2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,strpos($c,'>')>0?range(...explode(">",$c)):[$c]);},
[]
));
See the updated demo here: https://rextester.com/BWBYF59990
It's easy to create an empty array and fill it while loop a source
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$res = [];
foreach($array as $x) {
$separate = explode(">", $x);
if(count($separate) !== 2) {
// No char '<' in the string or more than 1
$res[] = $x;
}
else {
$res = array_merge($res, range($separate[0], $separate[1]));
}
}
print_r($res);
range function will help you with this:
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$newArray = [];
foreach ($array as $item) {
if (strpos($item, '>') !== false) {
$newArray = array_merge($newArray, range(...explode('>', $item)));
} else {
$newArray[] = $item;
}
}
print_r($newArray);

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 do I loop through a multidimensional array to retrieve keys where the value is one?

Here is my array: [["STR_License_Driver",1],["STR_License_Truck",0],["STR_License_Pilot",1],["STR_License_Firearm",0],["STR_License_Rifle",0]]
My goal is to make an array or string (unsure of best method) called results where the value of the licenses is 1.
For example: The results should be something like: STR_Licenses_Driver, STR_Licenses_Pilot.
I am currently using PHP Version 7, and Laravel Version 5.5
JSON Decode the $this->license and do the loop.
Whole code:
$licenses = $this->licenses;//This is your posted array string
$result = json_decode($licenses);
$licenses_with_1 = array();
foreach($result as $i){
foreach($i as $key => $value){
if($value == 1){
$licenses_with_1[] = $i[0];
}
}
}
print_r($licenses_with_1);
Result:
Array ( [0] => STR_License_Driver [1] => STR_License_Pilot )
I remember Python on your data structure.
Try my solution:
https://3v4l.org/nrfqZ
$licenses = [["STR_License_Driver",1],["STR_License_Truck",0],["STR_License_Pilot",1],["STR_License_Firearm",0],["STR_License_Rifle",0]];
Map over filtered array having second item equal to 1 to get the license names.
$filterVal = 1;
$licenseNames = array_map(
function ($item) { return $item[0]; },
array_filter(
$licenses,
function ($item) use ($filterVal) { return $item[1] === $filterVal; }
)
);
Then implode array of license names to join by glue string.
echo implode($licenseNames, ', ');

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

How do I combine both without any loop?

$data1 = "mathews,luks,john,ethan,neil";
$data2 = "80%,60%,78%,55%,62%";
want to combine both like
mathews = 80%
Luks = 60%
John = 78%
etc.... how to do this?? I want print result exactly like Mathews = 80%
http://us.php.net/manual/en/function.array-combine.php
$result = array_combine ( explode ( ',', $data1 ), explode ( ',', $data2 );
to extract:
if you know key name: echo $result ['john'];
if all: foreach ( $result as $key => $value ) { echo $key . ' : ' . $value; }
to gey list of keys: $list = explode ( ',', $data1 ) or $list = array_keys ( $result );
http://us.php.net/manual/en/function.array-keys.php
How about this...?
print_r(array_combine(explode(',',$data1),explode(',',$data2)));
$arr = array_combine(explode(',', $data1), explode(',', $data2));
Or
$names = explode(',', $data1);
$par = explode(',', $data2);
$arr = array();
foreach ($names as $idx=>$name)
{
$arr[$name] = $par[$idx];
}
Use the built in array_combine
You may consider using preg_split to the string:
$names = preg_split("/[,]+/", "mathews,luks,john,ethan,neil");
$percent = preg_split("/[,]+/", "80%,60%,78%,55%,62%");
Then you can use array_combine like many others suggest, or simply use 2 arrays $names and $percent along with the shared index, for example, $names[2] goes along with $percent[2].
As stated by bensui:
$data1 = "mathews,luks,john,ethan,neil";
$data2 = "80%,60%,78%,55%,62%";
$array = array_combine(explode(',',$data1), explode(',',$data2));
This will result in:
print_r($array);
Array
(
[mathews] => 80%
[luks] => 60%
[john] => 78%
[ethan] => 55%
[neil] => 62%
)
This will give you the ability easily update the assocaited scores simple by doing:
$array['mathews'] = '90%';
You can then use the array_slice I offered you earlier to discard john and ethan:
$newArray = array_slice($array, 2, 2);
This will give you:
print_r($newArray);
Array
(
[mathews] => 80%
[luks] => 60%
[neil] => 62%
)
Note: there is nothing wrong with using loops, the fact of the matter is they are often over used when there are methods built in to the language to solve many common problems.
If you are some kind of anti-loop fanatic, you could create a recursive function.
function no_loop_combine($data1,$data2,$index)
{
if($index == count($data1))
{
return '';
}
else
{
return $data1[$index] . ' = ' . $data2[index]
. '\n' . no_loop_combine($data1,$data2,$index + 1);
}
}
Then you just have to call your function specifying $index = 0, and you will get the result. Using array_combine probably is still using a loop, just masked by the fact that you are calling a function. Using recursion means there is no loop. Just realized that your initial input is a string, and not a loop. So you could call explode before passing it into the function as so:
no_loop_combine(explode(',', $data1 ),explode(',',$data2),0);

Categories