I need to compare an array that comes from a query, with a base array where I have the values that could have the array that comes from the query, the question is how to go through and compare the two arrays so that I get zero where the values do not match And give me the value of the array ?.
this is my code:
public function age_range_men()
{
$type = 'brands';
$id_array= 75;
$date_start= '2017-01-02 00:01:00';
$date_end='2017-03-31 23:59:59';
$datos = $this->statistics_model->range_age_men($type, $id_array, $date_start, $date_end);
$result = array();
foreach($datos as $dato) {
$result[] = array((string)$dato->rango, (int)$dato->conexiones );
}
$base= array(array('12 a 17'), array('18 a 24'),array('25 a 34'), array('35 a 44'), array('45 a 54'),array('55 a 64'),array('mas de 65'));
$res = array();
foreach ($base as $base1) {
// print_r($base1[0]);
// echo "<br>";
foreach ($result as $result2){
if ($base1[0] == $result2[0]){
}else{
echo 0;
break;
}
}
}
}
[The first line is $result and the second line is $base][1]
[1]: https://i.stack.imgur.com/LC5Ps.jpg
Here is my suggestion. Create an associative array for results. Make $base a list of keys rather than a strange multi-dimensional array. Check for the key in an array. I have the else echo 0 I have no idea what you want if it exists.
<?php
function age_range_men(){
$type = 'brands';
$id_array= 75;
$date_start= '2017-01-02 00:01:00';
$date_end='2017-03-31 23:59:59';
$datos = $this->statistics_model->range_age_men($type, $id_array, $date_start, $date_end);
$result = array();
foreach($datos as $dato) {
$result[(string)$dato->rango] = (int)$dato->conexiones; // Note this is now using a key
}
//This is no longer a multi-dimensional array just the keys we need
$base= array('12 a 17', '18 a 24','25 a 34', '35 a 44', '45 a 54','55 a 64','mas de 65');
$res = array();
foreach ($base as $key) {
if(array_key_exists($key, $results)){
//CODE???
} else {
echo 0;
}
}
}
age_range_men();
Related
I have a phone book array I get from a database, where everyone appears once with their stationary phone number and a second with their mobile number.
I need to make this an array where everyone has only one line, with their phone number and mobile number
//My array
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
//The result that should come out
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244','phone'=>''),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778','phone'=>'04472861558878')
);
I would do it the following way:
first I would generate a unique key that identify the row (in your case the name and the family, for example).
then check if a element with the same key exist, if it already exist merge the two component.
Optional if you only want an array of values transform the result with array_value function.
$dataArray = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
$result = [];
foreach($dataArray as $data){
//Just in case that the name or the family is not assigned (operator ??)
$key = ($data['name']??'').'-'.($data['family']??'');
$result[$key] = array_merge($result[$key]??[],$data);
}
//Optional, get only the array values
$result = array_values($result);
I did so
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
count($data) < 2 ? exit(): $data;
for($i=0;$i<count($data);$i++){
$array_unique[$i] = $data[$i]["name"];
$array_unique[$i] = $data[$i]["family"];
}
$array_unique = array_unique($array_unique);
if(count($array_unique) == 1){
$last_array[0]=$array_unique[0];
$last_array[0]["phone"]=$array_unique[0]["phone"];
}
else{
$array_uniqueKeys = array_keys($array_unique);
for($i = 0;$i < count($array_unique);$i++){
$firstIndex = $i + 1;
$firstIndex == count($array_unique) ? $nextKey = count($data) : $nextKey = $array_uniqueKeys[$firstIndex];
$paar = $nextKey - $array_uniqueKeys[$i];
$dataslice = array();
$i3=0;
for($i2 = $array_uniqueKeys[$i];$i2 < ($array_uniqueKeys[$i]+$paar);$i2++){
if(in_array($i2,$array_uniqueKeys)){
$last_array[$i]=$data[$i2];
}
else{
$last_array[$i]["phone"]=$data[$i2]["phone"];
}
$i3++;
}
}
}
print_r($last_array);
i will ask how to insert array if amount sub arrays not same, i have problem if the $arrays != 3 because in sub arrays 2 in arrays one
<?php
$arrays=array(
array('a','b'),
array('a','b','c'),
array('a','b','c')
);
$per=0;
for ($h=0; $h < count($arrays); $h++) {
if (count($arrays) > $per) {
$per= count($arrays);
}
}
$koneksi = new mysqli("127.0.0.1","root","","data");
$nil=array();
foreach ($arrays as $data) {
foreach ($data as $key => $value) {
$data[$key] = $data[$key];
}
$nil[]="('".implode("', '",$data). "')";
}
$insert="INSERT INTO datams (data1,data2,data3) VALUES ".implode(', ',$nil);
$queri=mysqli_query($koneksi, $insert);
if ($queri == true){
echo 'upload done'.PHP_EOL;
} else {
echo 'fail upload'.PHP_EOL;
}
i can't insert the data if sub array same, can help me ?
You will have to make the arrays the same length.
Create an empty array, then loop your existing array, adding the missing values using array_replace. After that, you can insert them.
$empty=['' , '' , ''];
foreach($array as $key => $tmp){
$array[$key] = array_replace($empty,$tmp);
// This replaces the values of $empty with those of $array that are set:
// ['','',''] replace wihh ['a','b','c'] gives ['a','b','c']
// ['','',''] replace with ['a','b'] gives ['a','b','']
}
You will end up with:
$arrays=array(
array('a','b','' ),
array('a','b','c'),
array('a','b','c')
);
Now you can insert the values;
EDIT
To make it more flexible (i.e the original array keeps changing), you first have to find the length of the longest array in $array.
$max=0;
foreach($array as $a) {
$c = count($a);
if( $c > $max) $max = $c;
}
$empty=array_fill(0,$max,'');
I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)
For example:
$arr = array(3,5,2,5,3,9);
I want to show only common elements i.e 3,5 as output.
Here's my attempt:
<?php
$arr = array(3,5,2,5,3,9);
$temp_array = array();
foreach($arr as $val)
{
if(isset($temp_array[$val]))
{
$temp_array[$val] = $val;
}else{
$temp_array[$val] = 0;
}
}
foreach($temp_array as $val2)
{
if($val2 > 0)
{
echo $val2 . ', ';
}
}
?>
--
Output --
3, 5,
Try the following:
$arr = array(3,5,2,5,3,9);
foreach($arr as $key => $val){
//remove the item from the array in order
//to prevent printing duplicates twice
unset($arr[$key]);
//now if another copy of this key still exists in the array
//print it since it's a dup
if (in_array($val,$arr)){
echo $val . " ";
}
}
Output:
3 5
Addition:
I guess that the reason you were asked to implement it yourself (without using built-in functions) was to avoid answers like:
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
$arrnew = array();
for($i=0;$i<count($arr);$i++)
{
for($j=$i+1;$j<count($arr);$j++)
{
if($arr[$i]==$arr[$j])
{
$arrnew[]=$arr[$j];
}
}
}
I have a nested array with valid numbers => data:-
$validData = array(array(1 => 'one data'),array(5 => '5 data'),array(15 => '15 data'),array(30 => 'thirty data'));
Let say I have a query value, $query = 14;
I want to first check if there's a 14, if not then go to the nearest option ABOVE.
I've been doing nearest item with max, array_keys and ranges. But, matching or going above for some reason I can't see the best way?
// in case your array keys are already sorted
$prevKey = key(current($validData));
foreach($validData as $data) {
$currentKey = key($data);
if ($currentKey == $query) {
// found !
echo $currentKey;
break;
}
else if ($currentKey > $query) {
echo $currentKey;
break;
}
$prevKey = $currentKey;
}
Assuming the array is sorted
$query = 14;
$arrayThatWeWant = null;
foreach ( $validData as $index=>$vdSubRay)
{
$ak = key($vsSubRay);
if ( $ak == $query )
{
$arrayThatWeWant = $vdSubRay;
break;
}
else if ( $ak > $query )
{
$arrayThatWeWant = $validData[$index-1];
break;
}
}