count same items in comma separated string in sql - php

Hi i have comma seperated id's in database.
I want to count/percentage them individually (GROUP BY) and wanna make pie chart. How to do it ?
Like, Example database picture is attached.
Id COUNT
1-----------6 OR some%
15----------3 OR some%
17----------2 OR some%
2-----------2 OR some%
6-----------2 OR some%
12----------1 OR some%

Try this
suppose you got data in $result
then
$result['count']=count(explode(",",$result['column_name']));

Beside the fact that your DB structure is a total mess you can try the following:
$arrData = [
"1","15,17","1","1","15,17","1","1","1,2","6,7,12,16","9,10","2,4,6,7","14,15,16"
];
$arrCounts = [];
array_walk($arrData, function($item, $key) use (&$arrCounts) {
foreach(explode(",",$item) AS $val)
{
if (!isset($arrCounts[$val])) $arrCounts[$val] = 0;
$arrCounts[$val]++;
}
});
ksort($arrCounts);
print_r($arrCounts);

Convert the variable containing the numbers seperated by a comma to an array with explode(), and count the items of the array.
$string = '1,2,3,4';
$array = explode(',',$string);
echo "String contains ".count($array)." items";

Related

if 2 array are equally individual value check but print value only one time

I HAVE 2 table IN DATABASE
user=>1st col=>user_id=>[1,2,3], 2nd col=>user_name=>[a,b,c]
image=>
1st col=>user_id=>[1,1,2,2,3],2nd col=>image_path=>[abc,sd,as,cd]
MY OUTPUT
i want to output like this
{ user_id=1
user_name=a
image_path=abc
sd}
{ user_id=2
user_name=b
image_path=as
cd} and so on....conti
i want userid only once means not repeated again of same user and all other detail print like above
First of all you need to JOIN your tables on the user_id column with JOIN image ON user.user_id = image.user_id and select the columns you need.
Then use array_reduce to collect all image pathes into an array of the specific row:
$final = array_reduce($sqlResult, function($result, $row){
if (!array_key_exists($row['user_id'], $result) {
$result[$row['user_id']] = $row;
$result[$row['user_id']]['image_path'] = [$row['image_path']];
} else {
$result[$row['user_id']]['image_path'][] = $row['image_path'];
}
return $result;
}, []);
The result will be your desired output.
You can first merge you array by array_merge() like this,
$new_array = array_merge($arr1,$arr2);
by this you will get array combination of both the arrays and then you need to make it unique by array_unique() method like this,
$final_array = array_unique($new_array);
I hope it helps.
EDIT ::
Oh i am sorry i misunderstands.
#Philipp Maurer answer is correct. as array_intersect() method give you the common values from both the arrays.
see the link array-intersect

Search multi-dimesional array and return specific value

Hard to phrase my question, but here goes. I've got a string like so: "13,4,3|65,1,1|27,3,2". The first value of each sub group (ex. 13,4,3) is an id from a row in a database table, and the other numbers are values I use to do other things.
Thanks to "Always Sunny" on here, I'm able to convert it to a multi-dimensional array using this code:
$data = '13,4,3|65,1,1|27,3,2';
$return_2d_array = array_map (
function ($_) {return explode (',', $_);},
explode ('|', $data)
);
I'm able to return any value using
echo $return_2d_array[1][0];
But what I need to be able to do now is search all the first values of the array and find a specific one and return one of the other value in i'ts group. For example, I need to find "27" as a first value, then output it's 2nd value in a variable (3).
You can loop through the dataset building an array that you can use to search:
$data = '13,4,3|65,1,1|27,3,2';
$data_explode = explode("|",$data); // make array with comma values
foreach($data_explode as $data_set){
$data_set_explode = explode(",",$data_set); // make an array for the comma values
$new_key = $data_set_explode[0]; // assign the key
unset($data_set_explode[0]); // now unset the key so it's not a value..
$remaining_vals = array_values($data_set_explode); // use array_values to reset the keys
$my_data[$new_key] = $remaining_vals; // the array!
}
if(isset($my_data[13])){ // if the array key exists
echo $my_data[13][0];
// echo $my_data[13][1];
// woohoo!
}
Here it is in action: http://sandbox.onlinephpfunctions.com/code/404ba5adfd63c39daae094f0b92e32ea0efbe85d
Run one more foreach loop like this:
$value_to_search = 27;
foreach($return_2d_array as $array){
if($array[0] == $value_to_search){
echo $array[1]; // will give 3
break;
}
}
Here's the live demo.

How can i unserialize an array and do insert query for each data?

I'm not used to work with arrays, and now i have to, and i need some help guys.
I have a list of absences,that contain multiples values. They are all ids (like 4,25,100...) separed by a ','.
I want to add every single id in a table (insert query),i know the simple methode :
Insert into table (columns..) Values(values1,value2,...),
(values1,value2,...),
(values1,value2,...),
(values1,value2,...)
But i dont know how to use it the the serialsed array.
Explode the string on the commas, then iterate over the resulting array. Understanding arrays is essential to PHP (and coding in general), so check out http://php.net/manual/en/language.types.array.php.
$string = '4,25,100';
$array = explode(',', $string);
foreach ( $array as $value ) {
$sql = "INSERT INTO `table` (`some_column`) VALUES ('".$v."')";
}

PHP - Extracting ids from a string to run against a function

I was wondering if someone could help me out.
Im extracting a string from my database which is formatted like so 4,3,1,7,38 etc etc ... its a dynamic array so it could be any number of numbers etc etc
What i need to do is extract each number and run it agains a function .. So for example each number represents a users id, i need to run each user id against a function and return a set result, so for each id i would neeed to run something like
$personsdetails = $this->random_model->get_user_details( $useridhere );
How would i go about getting each of the ids out of the array and running it over a loop to get each persons details?
Cheers
You can use explode and foreach over created array.
$userIds = explode(',', $yourstring);
foreach ($userIds as $userId) {
$personsdetails = $this->random_model->get_user_details( $userId );
}
$ids_raw = '1,2,3,4,5';
$ids = explode(',', $ids_raw);
foreach($ids as $id){
echo $id;
}
$var=explode(',',$database_value);
its comming in array
Because you're bringing in a single dimension array, I'd suggest using a for() loop (personal preference). The explode() function will split
a string by the first argument you give it. So in this case, explode is splitting the string in $userIDs by commas ','. Then we run each array element through your function.
$userIDs = '1,2,3';
$userIDs = explode(',',$userIDs);
for($x=0;$x<count($userIDs);$x++){
$personsdetails = $this->random_model->get_user_details($userIDs[$x]);
};

Php add duplicate values inside an array

I have an array which contain multiple values inside it, all i want is to find duplicate items and add the number of times they are inside an array. Here goes an example
$someVar = array('John','Nina','Andy','John','Aaron','John','Zack','Kate','Nina');
I want my final result to look like
John = 3;
Nina = 2;
and so on.
EDIT | These values are dynamic i have no idea what these names going to be.
Thanks
Use array_count_values() and array_filter() to achieve this.
$result = array_filter( array_count_values( $someVar), function( $el) {
return $el > 1;
});
$result will be an associative array containing the names as keys and the number of times they occur as values, but only if they were duplicated in the $someVar array.
Here is a demo showing the correct output.

Categories