I try to remove a prefix in array keys and every attempt is failing. What I want to achieve is to:
Having: Array ( [attr_Size] => 3 [attr_Colour] => 7 )
To Get: Array ( [Size] => 3 [Colour] => 7 )
Your help will be much appreciated...
One of the ways To Get:Array ( [Size] => 3 [Colour] => 7 ) From your Having: Array ( [attr_Size] => 3 [attr_Colour] => 7 )
$new_arr = array();
foreach($Your_arr as $key => $value) {
list($dummy, $newkey) = explode('_', $key);
$new_arr[$newkey] = $value;
}
If you think there'll be multiple underscores in keys just replace first line inside foreach with list($dummy, $newkey) = explode('attr_', $key);
If I understood your question, you don't have to use implode() to get what you want.
define(PREFIX, 'attr_');
$array = array('attr_Size' => 3, 'attr_Colour' => 7);
$prefixLength = strlen(PREFIX);
foreach($array as $key => $value)
{
if (substr($key, 0, $prefixLength) === PREFIX)
{
$newKey = substr($key, $prefixLength);
$array[$newKey] = $value;
unset($array[$key]);
}
}
print_r($array); // shows: Array ( [Size] => 3 [Colour] => 7 )
Because the first character that you'd like to retain in each key starts with an uppercase letter, you can simply left-trim lowercase letters and underscores and voila. To create a "mask" of all lowercase letters and the underscore, you could use a..z_, but because attr_ is the known prefix, _art will do. My snippet, admittedly, is narrowly suited to the asker's sample data, does not call explode() to create a temporary array, and does not make multiple function calls per iteration. Use contentiously.
Code: (Demo)
$array = [
'attr_Size' => 3,
'attr_Colour' => 7
];
$result = [];
foreach ($array as $key => $value) {
$result[ltrim($key, '_art')] = $value;
}
var_export($result);
Output:
array (
'Size' => 3,
'Colour' => 7,
)
Related
I have this array:
Array
(
[one] => Array
(
[a] => 0
[b] => 1
[c] => 1
[d] => 3
[e] => 1
)
[two] => Array
(
[a] => 0
[b] => 3
[c] => 1
[d] => 4
[e] => 1
)
[three] => Array
(
[a] => 3
[b] => 1
[c] => 2
[d] => 4
[e] => 1
)
)
And I want to convert it into single array with the values are the sums of every value inside the inner array, so it could be like this:
Array
(
[a] => 3
[b] => 5
[c] => 4
[d] => 11
[e] => 3
)
How to achieve it?
EDIT
This was the best what I've done:
$rest = array();
foreach($result as $key => $value){
if(is_array($value)) {
foreach($value as $k => $val){
$rest[$k] = array_sum($value);
}
}
}
But it returns all values to be the same, i.e all 9 on every inner key.
You can get the keys from the first child array with array_keys, and then use array_sum and array_column to generate the array of sums.
foreach (array_keys($your_array['one']) as $key) {
$sums[$key] = array_sum(array_column($your_array, $key));
}
array_column does require php >= 5.5.
Incidentally, what you already had was really close to working. If you change
$rest[$k] = array_sum($value);
to
$rest[$k] += $val;
It should be good to go. What you had before was repeatedly summing the entire sub-array and assigning it to each letter key, but you just needed to add the current value to that letter key.
$rest[$k] += $val; will work, but give you undefined index notices for the first sub-array. You can fix that by checking isset before assigning, like this:
$rest[$k] = isset($rest[$k]) ? $rest[$k] + $val : $val;
I would say modifying your original code to work this way would probably be better than redefining array_column if you can't use it.
You have multidimensional Array , that why have to use two loop for understanding in beginning level. First loop will get Every Object of Array , Second Array will get the Params of Object.
$finalArray = array();
for($i = 0;$i<count($array);$i++){ // GET ALL OBJECT FROM ARRAY
foreach($array[$i] as $key=>$value){ // GET ALL KEY FROM OBJECT
$finalArray[$key] += $array[$i][$key];
}
}
print_r($finalArray);
Work on all version of PHP
You can use array_sum and loop over the first dimension
foreach ($array as $key => $values) {
$newArray[$key] = array_sum($values);
}
Credit to Don't Panic's answer above and this answer which is providing array_column() alternative for PHP version < 5.5
// if array_column function don't exist, add array_column function
if (! function_exists('array_column')) {
function array_column(array $input, $columnKey, $indexKey = null) {
$array = array();
foreach ($input as $value) {
if ( ! isset($value[$columnKey])) {
trigger_error("Key \"$columnKey\" does not exist in array");
return false;
}
if (is_null($indexKey)) {
$array[] = $value[$columnKey];
}
else {
if ( ! isset($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not exist in array");
return false;
}
if ( ! is_scalar($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not contain scalar value");
return false;
}
$array[$value[$indexKey]] = $value[$columnKey];
}
}
return $array;
}
}
// sum up the values
$rest = array();
foreach($result as $key => $arr){
if(is_array($arr)) {
foreach($arr as $k => $val){
$rest[$k] = array_sum(array_column($result, $k));
}
}
}
I want to merge the keys of array based on values. This is my array.
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 0
[6] => 2
[7] => 2
)
I want output as
Array
(
[1,2,3] => 1
[4,6,7] => 2
[5] => 0
)
I have been brain storming entire day but couldn't find a solution. Any hint would be much appreciated.
WHAT I HAVE TRIED:
for($i=2;$i<=count($new);$i++){
if ($new[$i-1][1]==$new[$i][1]){
$same .= $new[$i-1][0].$new[$i][0];
}
}
echo $same;
But I am stucked. I am comparing the keys one by one but it's very complicated. I don't need the code. I only need the hint or logic. Anyone kind enough?
<?php
$old_arr = ["1"=>1,"2"=>1,"3"=>1,"4"=>2,"5"=>0,"6"=>2,"7"=>2];
$tmp = array();
foreach($old_arr as $key=>$value)
{
if(in_array($value, $tmp)){
$index = array_search($value, $tmp);
unset($tmp[$index]);
$tmp[$index.",".$key] = $value;
}else{
$tmp[$key] = $value;
}
}
ksort($tmp);
echo "<pre>";
print_r($tmp);
echo "</pre>";
?>
https://eval.in/529314
You can loop through array elements and create a new array with new structure. Please check the below code it may help you
$old_array = array(1=> 1,2 => 1,
3=> 1,
4 => 2,
5 => 0,
6 => 2,
7 => 2
);
$new_array = array();
foreach($old_array as $key => $value)
{
if(in_array($value,$new_array))
{
$key_new = array_search($value, $new_array);//to get the key of element
unset($new_array[$key_new]); //remove the element
$key_new = $key_new.','.$key; //updating the key
$new_array[$key_new] = $value; //inserting new element to the key
}
else
{
$new_array[$key] = $value;
}
}
print_r($new_array);
$arr = array(1 => 1, 2 => 1, 3 => 1, 4 => 2, 5 => 0, 6 => 2, 7 => 2);
$tmp = array();
foreach ($arr as $key => $val)
$tmp[$val][] = $key;
$new = array();
foreach ($tmp as $key => $val)
$new[implode(',', $val)] = $key;
First loop the original array through, creating a temporary array, where your original values are keys and values are the original keys as an array.
Then loop the temporary array, creating the new array, where the temporary array's values are imploded as keys.
There's no way to have an array of keys to a single value, but the other way around:
function flipWithKeyArray($arr){
$result = array();
foreach($arr as $key => $val){
if(!isset($result[$val]))
$result[$val] = array();
$result[$val][] = $key;
}
return $result;
}
This will flip your array and declare one array per value of your old array and then push the keys with the same value into each list.
For an array like this:
array(1=>1, 2=>1, 3=>1, 4=>2, 5=>2, 6=>2)
The result will look like this:
array(1=>array(1,2,3), 2=>array(4,5,6))
Hope it fits your need.
I have this array:
Array
(
[count] => 12
[6] => CN=G_Information_Services,CN=Users,DC=hccc,DC=campus
[7] => CN=WEBadmin,CN=Users,DC=hccc,DC=campus
[9] => CN=G_ISDept,CN=Users,DC=hccc,DC=campus
[10] => CN=STAFF,CN=Users,DC=hccc,DC=campus
)
and I want to create an array of values that consist of the value between the first CN= and , of each array value below.
I probably will have to loop thru the array above, do a regex search for the first occurrence of cn and the value that follows it
I am not sure what I am doing wrong.
I need the final result to be an array that resembles this:
array('G_Information_Services', 'WEBadmin', 'G_ISDept', 'STAFF');
Use preg_match on each of the array values to get only the first corresponding CN value.
$found = array();
foreach ($arr AS $values) {
if (preg_match('/CN=([^,]+),/',$values,$matches))
$found[] = $matches[1];
}
Output
Array
(
[0] => G_Information_Services
[1] => WEBadmin
[2] => G_ISDept
[3] => STAFF
)
Try this (not the most efficient way but it should work):
foreach ($array as $key => $value)
{
if (is_numeric($key))
{
$array[$key] = explode(',', $array[$key]);
$array[$key] = $array[$key][0];
$array[$key] = substr($array[$key], 3);
}
}
This gets the first value of CN= of each element of the array, it also ignores any DC= values.
$arr = array(
'count' => 12,
6 => 'CN=G_Information_Services,CN=Users,DC=hccc,DC=campus',
7 => 'CN=WEBadmin,CN=Users,DC=hccc,DC=campus',
9 => 'CN=G_ISDept,CN=Users,DC=hccc,DC=campus',
10 => 'CN=STAFF,CN=Users,DC=hccc,DC=campus'
);
$newArr = array();
foreach($arr as $key => $value)
{
if($key != 'count')
{
$temp = explode(',', $value);
foreach($temp as $item)
{
if(strpos($item, 'CN=') === 0)
{
$item = substr($item, 3 );
$newArr[] = $item;
break 1;
}
}
}
}
print_r($newArr);
I have this PHP one dimensional array:
Array
(
[Female--N] => 11
[Male--N] => 11
[Humans--N] => 11
[Adult--N] => 8
[Adolescent--N] => 8
[Reaction Time-physiology--N] => 6
[Acoustic Stimulation-methods--N] => 6
[Schizophrenia-genetics--Y] => 5
[Motion Perception--N] => 3
)
And i want a new array from this that looks like (i think this tow-dimensional..?):
Array
(
[Female][N] => 11
[Male][N] => 11
[Humans][N] => 11
[Adult][N] => 8
[Adolescent][N] => 8
[Reaction Time-physiology][N] => 6
[Acoustic Stimulation-methods][N] => 6
[Schizophrenia-genetics][Y] => 5
[Motion Perception][N] => 3
)
Can i use split method on key elements?
Little bit harder... i also need to split on the single '_' underscore, i did this to prevent the columns getting mixed up... But the example below doesn't do the job right...
$new_array = array();
foreach($MeshtagsArray as $key => $value) {
$parts = explode('__', $key, 2);
$parts2 = explode('_', $key, 2);
$new_array[] = array(
'discriptor' => $parts[0],
'qualifier' => $parts2[1],
'major' => $parts[1],
'#occurence' => $value
);
So the output should be something like:
[0] => Array
(
[discriptor] => Female
[qualifier] =>
[major] => N
[#occurence] => 11
........
[5] => Array
(
[discriptor] => Reaction Time
[qualifier] => physiology
[major] => N
[#occurence] => 6
Best regards,
Thijs
UPDATED
$new_array = array();
foreach($old_array as $key => $value) {
$parts1 = explode('--', $key, 2);
$parts2 = explode('-', $parts1[0], 2);
$new_array[] = array(
'descriptor' => $parts2[0],
'qualifier' => count($parts2) > 1 ? $parts2[1] : '',
'major' => $parts1[1],
'#occurence' => $value
);
}
$new_array will now be a numerically indexed, multidimensional array. Each top level key will contain an associative array of the elements you require.
In the future, feel free to explain the entire problem from the beginning, that way we can all better help you!
Explanation
According to php.net:
array explode ( string $delimiter , string $string [, int $limit ] )
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
The array in your problem is associative; it's keys are strings. This makes it is a simple matter to iterate over the array with foreach and explode the keys into parts. I use a limit parameter to ensure that there will be no more than two parts.
Also, since one delimiter is a doubled version of the other, we have to first explode on the double -- delimiter, and then explode on the single - delimiter.
Technically, we could have used a single explode—with no limit parameter—and the single - delimiter. Then we could have inferred which element part belonged where. However, sometimes there is no qualifier. To get around this problem, I've used two explodes, and a ternary operator that counts the returned number of elements from the second explode.
Try this function:
function convertArray($array)
{
$return = array();
foreach ($array as $key=>$value)
{
$exploded = explode('--', $key);
$return[$exploded[0]][$exploded[1]] = $value;
}
return $return;
}
Assuming you are splitting on -- and you want a two dimensional array, try the following.
foreach ($the_array as $key => $value) {
// split key into new indexes
$indexes = explode('--', $key);
if (count($indexes) == 2) {
// create new dimension and set value
$the_array[$indexes[0]][$indexes[1]] = $value;
// remove old index
unset($the_array[$key]);
}
}
Note: This converts on the original array and ensures the key contains --
my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.