Array formatting into a specific format? - php

I am getting an array like below after i formatted my result set into the below format.
Array
(
[0] => xxx#2456
[1] => xxx#2345
[2] => xxy#1234
[3] => xxy#123
[4] => xyz#3456
);
I want the result array from the above array like below. I am thinking how ot proceed using PHP string functions or is there any other way.
Note: There may be so many array elements like the above but i want unique elements after we added last digits after '#'.
Array
(
[0] => xxx#4801
[1] => xxy#1464
[2] => xyz#3456
);
Any ideas how to proceed....... In the above output array format xxx#4801 is sum of 2345 and 2456 of Input array.......

You can try
$unique = array_reduce($data, function ($a, $b) {
$c = explode("#", $b);
if (isset($a[$c[0]])) {
$d = explode("#", $a[$c[0]]);
$a[$c[0]] = $c[0] . "#" . ($c[1] + $d[1]);
} else {
$a[$c[0]] = $b;
}
return $a;
}, array());
echo "<pre>";
print_r(array_values($unique));
Output
Array
(
[0] => xxx#4801
[1] => xxy#1357
[2] => xyz#3456
)
Simple Online Demo

You can use array_unique() function and reindex it with array_values() Find the code for example.
array_unique($array)
array_values(array_unique($array));

Related

Convert index array into multidimensional associative/index array in php

My array looks like this
Array
(
[0] => A
[1] => B
[2] => C
)
Desired array
Array
(
[0] => Array
(
[0] => A
)
[1] => Array
(
[0] => B
)
[2] => Array
(
[0] => C
)
)
I have gone through these links but didn't able to figure out the solution being a newbie.
Convert associative array into indexed
convert indexed multidimensional array to associative multidimensional array
For example:
$new_array = array_map(
function ($v) { return [$v]; },
['A', 'B', 'C']
);
This is a blanket statement on how to get your desired array :
$desired_array = array(array("0"=>"A"), array("0"=>"B"), array("0"=>"C"));
However, dynamically, you could do the following :
//Assume $original_array = array("0"=>"A", "1"=>"B", "2"=>"C");
$desired_array = array(); // New Array
for($i = 0; $i < count($original_array); $i++){ // Loop over all elements in original array
array_push($desired_array, array("0"=>$original_array[$i])); // Place each valueable as an array in new desired array
}
$arrOld = ['A','B','C','D','E'];
$arrNew = [];
foreach($arrOld as $key => $value){
$arrNew[] = [$key => $value];
}

Sum of columns in multidimensional array without loops

I'm used to analysing data in R and have a hard time figuring out array in PHP.
Given the following array ($dat), what is the easiest way to get the total number of all females?
print("<pre>".print_r($dat,true)."</pre>");
Array
(
[0] => Array
(
[0] => female
[1] => blue
[2] => 62
)
[1] => Array
(
[0] => female
[1] => red
[2] => 22
)
[2] => Array
(
[0] => male
[1] => blue
[2] => 21
)
)
I'm doing this:
foreach($dat as $row) {
if($row[0]=='female') {
$females = $females + $row[2];
}
}
But there must be a way without loops!
Isn't there something like sum($dat[][2])?
Result for this sample should be 84
It seems I misinterpreted your question...
To obtain the sum, you can use array_reduce instead of a foreach loop (although it's not going to be much of an improvement):
array_reduce($dat, function($prev,$curr){return $prev+($curr[0]==='female'?$curr[2]:0);}, 0);
To obtain the number of elements containing 'female', You could use count with array_filter:
echo count(array_filter($dat, function($x){return in_array('female', $x);}));
This filters the array for any sub-arrays that contain the string female and returns the number of elements.
If you're sure that the string 'female' is always the zeroth element of the array, you could simplify the function slightly:
echo count(array_filter($dat, function($x){return $x[0]==='female';}));
You can array_reduce your array to a sum that way :
$array[0] = array('female', 2);
$array[1] = array('female', 5);
$array[2] = array('male', 2);
$sum = array_reduce($array, function ($value, $item) {
if ($item[0] == 'female') $value += $item[1];
return $value;
}, 0);
var_dump($sum);
Output :
7

Sorting by nth character in PHP

I'm trying to sort an array with school class names however when I use an alphabetical sorting function they wouldn't sort by grade year.
Alphabetical sorting:
Array
(
"LA2A",
"LB1A",
"LG2A",
"LG3A",
"LH2A",
"LH3A",
"LH4A",
"LH5A",
"LV4A",
"LV5A",
"LV6A"
)
This is what I would like to achieve:
Array
(
"LB1A",
"LA2A",
"LG2A",
"LH2A",
"LG3A",
"LH3A",
"LH4A",
"LV4A",
"LH5A",
"LV5A",
"LV6A"
)
So, how can I sort an array (in PHP) by first the third character, then the fourth and finally the second character.
Demo using usort
$test = array(
"LA2A",
"LB1A",
"LG2A",
"LG3A",
"LH2A",
"LH3A",
"LH4A",
"LH5A",
"LV4A",
"LV5A",
"LV6A"
);
//sort by first the third character, then the fourth and finally the second character.
function mySort($left, $right) {
$left = $left[2].$left[3].$left[1];
$right = $right[2].$right[3].$right[1];
return strcmp($left, $right);
}
usort($test, 'mySort');
$test is now :
Array (
[0] => LB1A
[1] => LA2A
[2] => LG2A
[3] => LH2A
[4] => LG3A
[5] => LH3A
[6] => LH4A
[7] => LV4A
[8] => LH5A
[9] => LV5A
[10] => LV6A
)
The easiest way to do this is to apply something like the https://en.wikipedia.org/wiki/Schwartzian_transform
$arr = ...;
function add_key($x) { return $x[2] . $x[3] . $x[1] . $x; }
function rem_key($x) { return substr($x, 3); }
$tmp = array_map("add_key",$arr);
sort($tmp);
$res = array_map("rem_key",$tmp);
add_key adjusts each string by copying the sort key to the front. Then we sort it. rem_key gets rid of the key.

PHP Get the first value of all arrays in a multidimensional array [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 1 year ago.
Here's a section my multidimensional array:
Array (
[0] => Array ( [0] => Height [1] => 40 )
[1] => Array ( [0] => Weight [1] => 15 )
[2] => Array ( [0] => Ctr_Percent [1] => 15 )
)
What would the syntax be for just printing height, weight, and ctr_percent? I don't mean echoing it like:
echo $array[0][0];
echo $array[1][0];
Is there a way to iterate through the entire multidimensional array and echo out the first value of each child array?
Supposing you use php 5.3:
$first_elements = array_map(function($i) {
return $i[0];
}, $data);
Otherwise you need to implement a callback function or just use plain old foreach
Here is a one-liner:
array_map('array_shift', $array);
Will return:
Array
(
[0] => Height
[1] => Weight
[2] => Ctr_Percent
)
And here is another one:
array_combine(array_map('array_shift', $temp), array_map('array_pop', $temp))
Will return:
Array
(
[Height] => 40
[Weight] => 15
[Ctr_Percent] => 15
)
Use array_column:
$result = array_column($array, 0);
foreach ($main_array as $inner_array){
echo $inner_array[0] . "\n";
}
foreach($array as $x) {
echo $x[0]."\n";
}
I think the function your looking for is reset() e.g.
array_map('reset', $array);
or
foreach ($array as $subarray)
echo reset($subarray)."\n";
Note that this works even if 0 is not the first index of the array. E.g. $a = [1=>5,0=>3]; echo reset($a); would still echo 5;.
The easiest way to do it using array_walk
function getFirstElement(&$val){
$val = $val[0];
}
array_walk($data,'getFirstElement');
Now if you print $data like print_r($data); you will get result as below
Array
(
[0] => Height
[1] => Weight
[2] => Ctr_Percent
)

Specifying object in PHP Array from JSON

I'm trying to use a specific object type from a JSON feed, and am having a hard time specifying it. Using the code below I grab and print the specific array (max) I want,
$jsonurl = "LINK";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json,true);
$max_output = $json_output["max"];
echo '<pre>';
print_r($max_output);
echo '</pre>';
And from the Array below, all I want to work with is the [1] objects in each array. How can I specify and get just those values?
Array
(
[0] => Array
(
[0] => 1309924800000
[1] => 28877
)
[1] => Array
(
[0] => 1310011200000
[1] => 29807
)
[2] => Array
(
[0] => 1310097600000
[1] => 33345
)
[3] => Array
(
[0] => 1310184000000
[1] => 33345
)
[4] => Array
(
[0] => 1310270400000
[1] => 33345
)
[5] => Array
(
[0] => 1310356800000
[1] => 40703
)
Well you could fetch those values with array_map:
$max_output = array_map(function($val) { return $val[1]; }, $json_output["max"]);
This requires PHP 5.3, if you use an earlier version, then you can use create_function to achieve similar results:
$max_output = array_map(create_function('$val', 'return $val[1];'), $json_output["max"]);
When you need to create new array which will contain only second values, you may use either foreach loop which will create it or use array_map() (just for fun with anonymous function available since php 5.3.0):
$newArray = array_map( function( $item){
return $item[1]
},$array);
Then you want to use last ("max" -> considering array with numeric keys) item, you can use end():
return end( $item);
And when you can process your data sequentially (eg. it's not part of some big getData() function) you can rather use foreach:
foreach( $items as $key => $val){
echo $val[1] . " is my number\n";
}
After you get $max_output...
for( $i = 0; $i < length( $max_output ); $i++ ) {
$max_output[$i] = $max_output[$i][1];
}
try this:
$ones = array();
foreach ($max_output as $r)
$ones[] = $r[1];

Categories