check array key and value exist or not within loop - php

I have one foreach like this
$ret=array();
foreach($temp as $k=>$v)
{
$thv=mysql_fetch_array(mysql_query(" SOMEQUERY "));
$ret[]=$thv;
}
Here im pushing every output of $thv to $ret like $ret[]=$thv;
and output of $ret is,
[1] => Array
(
[0] => 701
[id] => 701
[1] => 1180
[media_image_id] => 1180
[2] => George Cumming - Session 1
[name] => George Cumming - Session 1
[3] =>
[preparation] =>
[4] =>
[description] =>
[5] =>
[coaching_points] =>
[6] =>
[progressions] =>
)
[2] => Array
(
[0] => 701
[id] => 701
[1] => 1180
[media_image_id] => 1180
[2] => George Cumming - Session 1
[name] => George Cumming - Session 1
[3] =>
[preparation] =>
[4] =>
[description] =>
[5] =>
[coaching_points] =>
[6] =>
[progressions] =>
)
Here id=>701 repeating, so what i want to do is, remove duplicate values from array but within that foreach loop.
Like,
if(id=>701 NOT EXIST IN $ret)
{
$ret[]=$thv;
}
SO that way no need to create another foreach. Anyone have idea how to do this in php?

I've an idea - use the id as the key of $ret. Example:
$ret=array();
foreach($temp as $k=>$v)
{
$thv=mysql_fetch_array(mysql_query(" SOMEQUERY "));
if (!isset($ret[$thv['id']])){
$ret[$thv['id']]=$thv;
}
}
If you still want 0..n to be the keys of $ret, you can do like this:
$ret = array_values($ret);

$ret = array();
$ids = array();
foreach($temp as $k => $v) {
// Run query
$thv = mysql_fetch_array(mysql_query(" SOMEQUERY "));
// Check if id present
if (!in_array($thv['id'], $ids)) {
// Not present, add to arrays
$ids[] = $thv['id'];
$ret[] = $thv;
}
}

Try this code.
$ret=array();
foreach($temp as $k=>$v)
{
$temp =array_column($ret,'id');
$thv=mysql_fetch_array(mysql_query(" SOMEQUERY "));
if(!in_array($thv['id'],$temp)){
$ret[]=$thv;
}
}

Related

Filter multidimensional multilevel array to uniq

I have the next probleme, i want to filter a multidimensional and multi level array with for the uniqe one.
An example:
Array
(
[Home] => Array
(
[Kids] => Array
(
[For sleeping] => Array
(
[0] => Sleeping Bags
[1] => mattress
[2] => mattress
[3] => mattress
[4] => Beds
[5] => Beds
[6] => Beds
[..]
The befored array i want to make it with the uniqe values.
I don't know if this is the fastest / shortest answer, but the code below might work for you:
#Function to make a multidimensional array unique
function makeUnique(&$array)
{
foreach($array as $key => &$value)
{
if(is_array($value))
{
makeUnique($value);
$value = array_unique($value);
}
}
return $array;
}
#Example of your array
$exampleArray = Array(
'Home' => Array(
'Kids' => Array(
'For sleeping' => Array(
0 => 'Sleeping Bags',
1 =>'mattress',
2 =>'mattress')
)
)
);
#Make the array unique and print the results
makeUnique($exampleArray);
print_r($exampleArray);
I have resolved this problem. The solution for this problem is:
$test = Array
(
[Home] => Array
(
[Kids] => Array
(
[For sleeping] => Array
(
[0] => Sleeping Bags
[1] => mattress
[2] => mattress
[3] => mattress
[4] => Beds
[5] => Beds
[6] => Beds
[..]
foreach ($test as $key=>$value){
foreach ($value as $key2 => $value2) {
foreach ($value2 as $key3=>$value3) {
$cat[$key][$key2][$key3]= array_unique($value3);
}
}
}

list and count elements in array php

I have the following array and am trying to loop through it with php, generate a list of the "Type" and count how many. The Type is the key, but there will be unique values such as Call, To-do, Meeting, Proposal, etc. My goal is to have the following out put:
Call 2
To-do 1
Meeting 3
Proposal 4
The above are not the values that will be output from the following array, but I wanted you to have an idea of what I am trying to accomplish. Please help!
Array (
[0] => Array (
[0] => Call
[Type] => Call
[1] => fxxxx#xxxxentllc.com
[EmailAddress] => xxxxr#xxxxentllc.com
[2] => 3xxxx00
[Phone] => 31xxxx00
[3] => 31xxxx871
[MobilePhone] => 31xxxx871
[4] => 102795
[CustomerID] => 102795
[5] => Nortxxxxal
[Company] => Noxxxxal
[6] => Frank
[FirstName] => Frank
[7] => Syxxxxer
[LastName] => Sxxxxter
[8] => 3
[Priority] => 3
[9] => invite to Haxxxxales for lunch
[Details] => invite to Hafxxxxales for lunch
[10] => 4503
[ActivityID] => 4503
[11] => 05/23/13
[DueDate] => 05/23/13
)
[1] => Array (
[0] => To-do
[Type] => To-do
[1] => fsxxxxer#summxxxxntllc.com
[EmailAddress] => fsxxxxer#summixxxxtllc.com
[2] => 315xxxx000
[Phone] => 3154xxxx0
[3] => 315xxxx1
[MobilePhone] => 315xxxx1
[4] => 102795
[CustomerID] => 102795
[5] => Norxxxxl
[Company] => Norxxxxcal
[6] => Frxxxxk
[FirstName] => Fxxxxk
[7] => Sxxxxr
[LastName] => Syxxxxer
[8] => 3
[Priority] => 3
[9] => find out who contact is for xxxxdical center
[Details] => find out who contact is foxxxxcal center
[10] => 4504
[ActivityID] => 4504
[11] => 05/23/13
[DueDate] => 05/23/13
)
)
This should do it:
$type_counts = array_count_values(array_map(function($x) {return $x['Type'];}, $array));
The array_map will return an array containing all the Type elements, then array_count_values will count the number of each of these and return this as an associative array.
something along the lines of:
foreach ($array as $key => $value) {
if (isset($result[$key])) {
$result[$key]++;
} else {
$result[$key] = 1;
}
}
if it is a muldi-dimensional array, just put another for each in there but that should give you an idea
$types = array();
foreach($array as $item) {
isset(${$item['Type']}) ? ${$item['Type']}++ : ${$item['Type']} = 1;
if(!in_array($item['Type'], $types) {
$types[] = $item['Type'];
}
foreach($types as $type) {
echo "$type ${$type}\n";
}
I think you can loop in your array and count each occorrence
$Call = 0;
$To_do = 0;
$Meeting = 0;
$Proposal = 0;
foreach($array as $data)
{
if($data['Type'] == 'Call')
{
$Call++;
} else if($data['Type'] == 'To-do')
{
$To_do++;
} else if($data['Type'] == 'Meeting')
{
$Meeting++;
} else if($data['Type'] == 'Proposal')
{
$Proposal++;
}
}
In this way you will have stored in each variable $Call $To_do $Meeting $Proposal its relative count
you can use (array_count_values($array));
http://php.net/manual/en/function.array-count-values.php
This gives count of all the keys in an array.
If you want only for the specific keys then use foreach loop
The one Petros mentioned is the best way to do it.
I would do something along the lines of:
$your_array = /* Your Array */
$types_count = array();
foreach ($your_array as $type_array){
$types_count[$type_array['Type']]++;
}

Sort multidimensional Array with an index

I have the following array and I want to sort all the records with total in descending order. Can anyone tell me the php code or pseudo code for doing it.
Array
(
[reg_id] => Array
(
[0] => 5
[1] => 7
[2] => 17
[3] => 18
[4] => 19
[5] => 20
[6] => 34
)
[name] => Array
(
[0] => employee1
[1] => employee6
[2] => employee3
[3] => employee4
[4] => employee2
[5] => empoyee5
[6] => employee9
)
[test_w] => Array
(
[0] => 21/30
[1] => 15/30
[2] => 27/30
[3] => 16.5/30
[4] => 21/30
[5] => 18/30
[6] => 12/30
)
[intr_w] => Array
(
[0] => 8/10
[1] => 6/10
[2] => 9/10
[3] => 9/10
[4] => 3.3/10
[5] => 7/10
[6] => 0/10
)
[exp_w] => Array
(
[0] => 2.5/5
[1] => 4/5
[2] => 4.35/5
[3] => 4.5/5
[4] => 4.8/5
[5] => 4.5/5
[6] => 0/5
)
[educ_w] => Array
(
[0] => 37.41/55
[1] => 44.14/55
[2] => 33.27/55
[3] => 38.43/55
[4] => 34.52/55
[5] => 46.11/55
[6] => 43.66/55
)
[total] => Array
(
[0] => 68.91
[1] => 69.14
[2] => 73.62
[3] => 68.43
[4] => 63.62
[5] => 75.61
[6] => 55.66
)
)
Use this function should solve the problem
function multisort($array, $key, $sort_flags = SORT_REGULAR) {
if (is_array($array) && count($array) > 0) {
if (!empty($key)) {
$mapping = array();
foreach ($array as $k => $v) {
$sort_key = '';
if (!is_array($key)) {
$sort_key = $v[$key];
} else {
// #TODO This should be fixed, now it will be sorted as string
foreach ($key as $key_key) {
$sort_key .= $v[$key_key];
}
$sort_flags = SORT_STRING;
}
$mapping[$k] = $sort_key;
}
asort($mapping, $sort_flags);
$sorted = array();
foreach ($mapping as $k => $v) {
$sorted[] = $array[$k];
}
return $sorted;
}
}
return $array;
}
For Example:
$result=multisort($array,$sort_flags = DESC);
The simplest (but least efficient) would be a simple bubble sort
Pseudo code
for( $i from 0 to count($arr[total])):
for( $j from 0 to count(...)):
if($arr[total][$i] < $arr[total][$j]):
//SWAP VALUES AT i AND j
$this->swap($arr[total][$i],$arr[total][$j]);
$this->swap($arr[name][$i],$arr[name][$j]);
$this->swap($arr[reg_id][$i],$arr[reg_id][$j]);
// etc for all required fields
endif;
endfor;
endfor;
SWAP FUNCTION (PASS VALUES BY REFERENCE SO THEY WILL GET CHANGED)
function swap(&$i, &$j){
$t=$i;
$i=$j;
$j=$t;
}
Since those seem to be fields related to an entity, the best answer I can give you is to build better data structures. By example, you should build an Employee (or whatever entity you are representing there) class containing those fields:
class Employee
{
public $reg_id;
public $name;
public $test_w;
public $intr_w;
public $exp_w;
public $educ_w;
public $total;
}
and then keep an array of Employee's. What if you had another field that in turn was an array? I know my answer doesn't address the actual sorting, I'm just saying your way of keeping the data can get really dirty really quick.
I have sort array with the following function.
function msort($array, $key_s) {
$arraynew = $array;
foreach($array as $key=>$val){
if($key == $key_s){
for($i=0; $i<count($val); $i++){
for($j=0; $j<count($val); $j++){
if($val[$i] > $val[$j]){
$temp = $val[$i];
$val[$i] = $val[$j];
$val[$j] = $temp;
// swap all values
foreach($arraynew as $arrKey=>$arrVal){
$temp = $arraynew[$arrKey][$i];
$arraynew[$arrKey][$i] = $arraynew[$arrKey][$j];
$arraynew[$arrKey][$j] = $temp;
}
}
}
}
}
}
return $arraynew;
}

Convert associative array into indexed

Ive seen a few examples by using array_values, but cant quite make out how to get it to work...
I have an associative array thats passed via POST, I need to convert it into a indexed array...
My print_r($_POST) gives me this... I need all of this put into an indexed array :)
Array (
[fieldnames] => 36771X21X198|36771X21X199|36771X21X200|36771X21X201|36771X21X202
[36771X21X198] => 3434343
[display36771X21X198] => on
[36771X21X199] => 5656565
[display36771X21X199] => on
[36771X21X200] => 89898989
[display36771X21X200] => on
[36771X21X201] => 90909090
[display36771X21X201] => on
[36771X21X202] => 12121212
[display36771X21X202] => on
[move] => movesubmit
[move2] => ONLINE Submit
[thisstep] => 1
[sid] => 36771
[token] => 1234567890
)
Observe this amazing way to convert your $_POST into a numerically indexed array:
$numerical = array_values($_POST);
but what if you want to preserve your keys? Perhaps you want something like this?
$numerical = array();
$sep = ':';
foreach($_POST as $k=>$v)
{
$numerical[] = $k.$sep.$v;
}
$numerical will then have:
Array
(
[0] => fieldnames:36771X21X198|36771X21X199|36771X21X200|36771X21X201|36771X21X202
[1] => 36771X21X198:3434343
[2] => display36771X21X198:on
[3] => 36771X21X199:5656565
[4] => display36771X21X199:on
[5] => 36771X21X200:89898989
[6] => display36771X21X200:on
[7] => 36771X21X201:90909090
[8] => display36771X21X201:on
[9] => 36771X21X202:12121212
[10] => display36771X21X202:on
[11] => move:movesubmit
[12] => move2:ONLINE Submit
[13] => thisstep:1
[14] => sid:36771
[15] => token:1234567890
)
or, for my final example:
$fieldnames_original = explode('|', $_POST['fieldnames']);
$fieldnames_actual = array();
$values = array();
foreach($_POST as $k=>$v)
{
if($k!='fieldnames')
{
$fieldnames_actual[] = $k;
$values[] = $v;
}
}
which will set 3 arrays:
$fieldnames_original:
Array
(
[0] => 36771X21X198
[1] => 36771X21X199
[2] => 36771X21X200
[3] => 36771X21X201
[4] => 36771X21X202
)
$fieldnames_actual:
Array
(
[0] => 36771X21X198
[1] => display36771X21X198
[2] => 36771X21X199
[3] => display36771X21X199
[4] => 36771X21X200
[5] => display36771X21X200
[6] => 36771X21X201
[7] => display36771X21X201
[8] => 36771X21X202
[9] => display36771X21X202
[10] => move
[11] => move2
[12] => thisstep
[13] => sid
[14] => token
)
and $values:
Array
(
[0] => 3434343
[1] => on
[2] => 5656565
[3] => on
[4] => 89898989
[5] => on
[6] => 90909090
[7] => on
[8] => 12121212
[9] => on
[10] => movesubmit
[11] => ONLINE Submit
[12] => 1
[13] => 36771
[14] => 1234567890
)
function
function array_default_key($array) {
$arrayTemp = array();
$i = 0;
foreach ($array as $key => $val) {
$arrayTemp[$i] = $val;
$i++;
}
return $arrayTemp;
}
Pass the associative array as a parameter and it will convert into the default index of the array. For example: we have Array('2014-04-30'=>43,'2014-04-29'=>41) after the call to the function the array will be Array(0=>43,1=>41).
Recursive assoc to indexed converter tested on a small array.
function assoc2indexedMulti($arr) {
// initialize destination indexed array
$indArr = array();
// loop through source
foreach($arr as $val) {
// if the element is array call the recursion
if(is_array($val)) {
$indArr[] = assoc2indexedMulti($val);
// else add the value to destination array
} else {
$indArr[] = $val;
}
}
return $indArr;
}

PHP Array handling for first children

I'm so tired of arrays today - thrown me all over the place.
So, here's the output of an array:
Array
(
[2010091907] => Array
(
[home] => Array
(
[score] => Array
(
[1] => 7
[2] => 17
[3] => 10
[4] => 7
[5] => 0
[T] => 41
)
[abbr] => ATL
[to] => 2
)
Array
(
[2010091909] => Array
(
[home] => Array
(
[score] => Array
(
[1] => 7
[2] => 17
[3] => 10
[4] => 7
[5] => 0
[T] => 41
)
[abbr] => ATL
[to] => 2
)
Array
(
[2010091901] => Array
(
[home] => Array
(
[score] => Array
(
[1] => 7
[2] => 17
[3] => 10
[4] => 7
[5] => 0
[T] => 41
)
[abbr] => ATL
[to] => 2
)
I'm going to be writting a preg_match to iterate each [2010091907], but before I can, I do not understand how to get this piece of information, or how to call it. I'd be doing something like:
$json=json_decode($data,true);
foreach ($json['dont-know-what-to-call-it'] as $key => $value) {
echo "Key: ".$key."; Value: ".$value."<br />";
}
I just don't know how to call each one of those [2010091901] blocks, like what name I'm suppose to call them as. I know how to call the stuff under score, since it's named "score", and the data is under all that. I don't know how to get the key/value of the initial "sections" of the array. In the end, I'm going to want to grab each [2010091901], manipulate/use the data that is inbetween each one of the [2010091901], and then go to the next "record".
$date_keys = array_keys($json) would give (0 => 2010091907, 1 => 2010091909, ...) . then you could do
foreach ($date_keys as $d) {
foreach ($json[$d] as $key => $value) {
...
Also, if you do not actually need the indices of the outer array (the date values - 2010091907, etc) than you could just do
foreach ($json as $j) {
foreach ($j as $key => $value) {
...
ignoring the keys of $json
Can't you just nest foreach()s?
foreach($jsondata as $somedate => $value){
//do you actually need $somedate?
foreach($value['home']['score'] as $score){
echo $score.PHP_EOL;
}
}
You can just do
$json = json_decode($data, true);
foreach($json as $ymd => $data)
{
// $ymd = [2010091907, 2010091909,… ]
// $data is the array starting with the key home. so $data['home']['score'][1] = 7 for the first iteration
}
This answer your question? It's not 100% clear what you're asking

Categories