remove integer index an array - php

I am working on a website where we need to remove the index of an array where type is integer.
Have you any idea or suggestion regarding.
My array looks like this :
Array
(
[0] => first
[first] => second
[1] => second
[second] => second
[2] => third
[third] => third
[3] => forth
[forth] => v
[4] => fifth
[fifth] => fifth
)
How we can remove integer index from array.One more thing to note that we have not static array we do not know how many index is there.
Need like this :
Array
(
[first] => second
[second] => second
[third] => third
[forth] => v
[fifth] => fifth
)

Database Solution:
To get only the associative array from mysql database use: mysqli_fetch_assoc() instead of mysqli_fetch_array().
mysqli_fetch_array() fetches the entire array - integer indexes as well as column names as keys.
mysqli_fetch_assoc() only fetches the column names as keys. - thus getting rid of integer keys.
General Solution:
To do what you asked in general I would use:
foreach($array as $key => $value){
if(is_numeric($key)) unset($array[$key]);
}
You can also use is_int() if you like..

Another way to do this :-
$array1 = array("6566"=>"zd xf", "2"=>2, "c"=>3, "d"=>4, "e"=>5);
$keys=array_filter(array_keys($array1), "is_numeric");
$out =array_diff_key($array1,array_flip($keys));
print_r($out);
output :
Array
(
[c] => 3
[d] => 4
[e] => 5
)

remove the integer index value of array.
$array1=array();
$array = array(0 => first,first => second,1 => second,second => second,2 => third,third => third,3 => forth,forth => v,4 => fifth,fifth => fifth);
foreach ($array as $key=>$value){
if(gettype($key)=='integer'){
unset($key);
unset($value);
}else{
$array1[$key]=$value;
}
}
print_r($array1);
out put like this.
Array
(
[first] => second
[second] => second
[third] => third
[forth] => v
[fifth] => fifth
)

Related

merging array in CI 3

I want to merge two arrays in order to get the data as per my requirement.
I am posting my result, please have a look.
First array:
Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
)
)
Second array:
Array
(
[0] => Array
(
[user_id] => 9c2e00508cb28eeb1023ef774b122e86
[car_id] => 14783
[status] => favourite
)
)
I want to merge the second array into the first one, where the value at key car_id matches the equivalent value; otherwise it will return that field as null.
Required output:
<pre>Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
[fav_status] => favourite
)
)
Since the merge is so specific I would try something like this:
foreach ($array1 as $index => $a1):
foreach ($array2 as $a2):
if ($a1['car_id'] == $a2['car_id']):
if ($a2['status'] == "favourite"):
$array1[$index]['fav_status'] = "favourite";
endif;
endif;
endforeach;
endforeach;
You might be able to optimize the code more but this should be very easy to follow...
Another way to achieve this without using the index syntax is to reference the array elements in the foreach by-reference by prepending the ampersand operator:
foreach($firstArray as &$nestedArray1) {
foreach($secondArray as $nestedArray2) {
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1['fav_status'] = $nestedArray2['status'];
}
}
}
You can see it in action in this Playground example.
Technically you asked about merging the arrays. While the keys would be different between the input arrays and the desired output (i.e. "status" vs "fav_status"), array_merge() can be used to merge the arrays.
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 = array_merge($nestedArray1, $nestedArray2);
}
Playground example.
Additionally the union operators (i.e. +, +=) can be used.
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator1
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 += nestedArray1;
}
Playground example.
1http://php.net/manual/en/function.array-merge.php#example-5587

Put a key of end of an array in php

I have this array:
Array
(
[0] => Array
(
[date] => 2016-03-08
[value] => Array
(
[key_1] => Array
(
[test_1] => 1
[test_2] => 10
[test_3] => 1000
[test_4] => 200
)
[key_2] => Array
(
[test_1] => 1
[test_2] => 15
[test_3] => 1500
[test_4] => 100
)
)
)
Now I have another array :
Array
(
[key_3] => Array
(
[test_1] =>
[test_2] =>
[test_3] =>
[test_4] => 1
)
)
I want to add this last array in the first array.
I try like this : array_push($ymlParsedData[]['value'], $a_big_gift); but not work. Can you help me please ?
You can't use $ymlParsedData[] for accessing specific element, it is a shorthand for pushing data to array.
You can use either
// NB! array_push() just adds the values, key 'key_3' is removed
array_push($ymlParsedData[0]['value'], $a_big_gift);
or
// will keep key 'key_3'
$ymlParsedData[0]['value']['key_3'] = $a_big_gift['key_3'];
or
// use array_merge() instead
$ymlParsedData[0]['value'] = array_merge($ymlParsedData[0]['value'], $a_big_gift);
A complicated answer, but this might solve your issue:
$key_name = array_keys($a_big_gift)[0];
$ymlParsedData[0]['value'][$key_name] = $a_big_gift[$key_name];
echo '<pre>'; print_r($ymlParsedData); exit;
Note: For making it dynamic and for more than one value of $a_big_gift, you need to loop it and achieve your result.
Try this
array_push($ymlParsedData[0]['value'], $a_big_gift['key_3']);

Array_Unique filtering

I have an multidimensional array:
Array
(
[0] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Other Cereals
[IName] =>
[Date] => 2013-02-05
)
[1] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Porridge
[IName] => Oats,Milk,Sugar
[Date] => 2013-02-06
)
[2] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Porridge
[IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
[Date] => 2013-02-05
)
)
And I am trying to use array unique to filter this
[IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
I am having no luck. How can I filter the duplicates?
Cheers.
If you filter input and therefore don't have extra spaces in IName field, you can use something as simple as this for filtering:
$array[2]['IName'] = implode(',', array_unique(explode(',', $array[2]['IName'])));
The problem is that you habe in array two Oats,Milk,Sugar as element of IName, in array three you have Oats,Milk,Sugar,Oats,Milk,Sugar. This is not the same!
"Oats,Milk,Sugar"=="Oats,Milk,Sugar,Oats,Milk,Sugar" (or "Oats,Milk,Sugar".equals("Oats,Milk,Sugar,Oats,Milk,Sugar")) is false.
If you want to have it unique you have to explode the single results and then do a unique on it or you have to store the single values in seperate fields...
BTW: Here is a link how to remove duplicates from a multi dimensional array How to remove duplicate values from a multi-dimensional array in PHP
I am not sure if a function exists for that, here is a simple solution,
you can loop the array, and get the result of each value, then explode result, and insert it into an array.
then use the array_unique function.
try this:
$result = array();
foreach($arrays as $array)
{
$tmp = $array['IName'];
$tmp2 = explode(',',$tmp);
foreach ($tmp2 as $t)
{
$result[]=$t;
}
}
$array_unique = array_unique($result);

PHP sort array using another array no keys

Hello i have an array in php
Array
(
[0] => red
[1] => blue
[2] => green
[3] => yellow
[4] => purple
[5] => white
)
and i want to sort it using that array
Array
(
[0] =>
[1] => 0
[2] => -1
[3] => -5
[4] => -5
[5] => 9
)
so i want the element with the greatest value on the second array to come first on the first array not its value from the second array but the element it self from the first array to move in the first position on the first array! The second bigger to the second place etc.. elements with the same value don't care me how they will be arranged!
the output i want to get is
Array
(
[0] => white
[1] => blue
[2] => green
[3] => yellow
[4] => purple
[5] => red
)
You can use array_multisort() :
$ar1 = array(/* your SO links */);
$ar2 = array(/* your numbers */);
array_multisort($ar2, SORT_DESC, $ar1);
Documentation here
Use array_multisort.
see http://www.php.net/manual/fr/function.array-multisort.php, follow the "Exemple #1 Trier plusieurs tableaux"
Cordially
Lets call your arrays are $dataArray, and $sortArray respectively
asort($sortArray);
foreach ( $sortArray as $key=>$val ) {
$newArray[] = $dataArray[$key];
}
If you need it reversed, just add in a call to array_reverse() at the end.
I think what the OP wants is to sort the first array by the second array's values.
IE- the second array is the vote count for the first array's web pages.
This could be solved more simply if in the first array you have each element as an array with two elements in it, webpage & vote count
$pages = Array
(
array(
'page' => 'http://stackoverflow.com/questions/640805/open-source-ios-components-reusable-views-controllers-buttons-table-cells-e',
'count' => 0
)
array(
'page' => 'http://stackoverflow.com/questions/3889634/fast-and-lean-pdf-viewer-for-iphone-ipad-ios-tips-and-hints',
'count' => -1
)
// etc for the rest...
)
But since the question asked how to do it in the current data structure:
$sorted_values = asort($pages);
$new_pages = array();
$sorted_keys = array_keys($sorted_values);
foreach($sorted_keys as $page_key)
array_push($new_pages, $pages[$page_key]);

Reducing multidimensional array

I have the following multidimensional array:
Array
(
[0] => Array
(
[area] => 5
[estante] => 5
[anaquel] => 5
[no_caja] => 5
[id_tipo] => 3
[nombre_tipo] => Administrativo
)
[1] => Array
(
[area] => 5
[estante] => 5
[anaquel] => 5
[no_caja] => 5
[id_tipo] => 1
[nombre_tipo] => Copiador
)
[2] => Array
(
[area] => 5
[estante] => 5
[anaquel] => 5
[no_caja] => 5
[id_tipo] => 2
[nombre_tipo] => Judicial
)
)
and I want to reduce it by having all the different values (intersection) between them. The dimension of the array may change (I'm retrieving the info from a database). I have thought in using functions like array_reduce and array_intersect, but I have the problem that they work only with one-dimension arrays and I can't find the way to pass an indefinite (not previous known) number of parameters to these function. I'd like to have an output like this:
Array([0]=>Copiador, [1]=>Administrativo, [2]=>Judicial).
How can I do this?
Thanks in advance.
$arr=array(
array (
'area' => 5 ,
'estante' => 5 ,
'anaquel' => 5,
'no_caja' => 5,
'id_tipo' => 3,
'nombre_tipo' => 'Administrativo'),
array (//etc.
)
);
$fn=function(array $a, $k){
if(array_key_exists($k,$a)) return $a[$k];
};
$b=array_map($fn,$arr,array_fill(0,count($arr),'nombre_tipo'));
print_r($b);
/*
Array
(
[0] => Administrativo
[1] => Copiador
[2] => Judicial
)
*/
$reduced = array();
foreach ($oldarray as $value) {
$reduced[] = $value['nombre_tipo'];
}
Although, a better solution may be to just modify your SQL query so you get the correct data to begin with.
Note: you can also do it with array_reduce, but I personally prefer the method above.
$reduced = array_reduce($oldarray,
function($a, $b) { $a[] = $b['nombre_tipo']; return $a; },
array()
);
This task is exactly what array_column() is for -- extracting columnar data.
Call this:
var_export(array_column($your_array, 'nombre_tipo'));
This will output your desired three-element array. ...I don't understand the sorting in your desired output.
Seems like you want array_map
$newArr = array_map(function($a) {
return $a['nombre_tipo'];
}, $oldArr);
var_dump($newArr);

Categories