I have an array like this :
Array (
[0] => Array (
[tsk_hours_spent] => 23425.00
)
[1] => Array (
[tsk_hours_spent] => 2.00
)
[2] => Array (
[tsk_hours_spent] => 0.00
)
[3] => Array (
[tsk_hours_spent] => 0.00
)
[4] => Array (
[tsk_hours_spent] => 0.20
)
)
I want results seperated based on '.' into two array
ie.,
Before dot one array and after dot one array
eg:
First array will be : 23425,2,0,0,0
Second array will be : 00,00,00,00,20
Try This
<?php
$tsk_hours_spent = array(array('tsk_hours_spent'=>'23425.00'),array('tsk_hours_spent'=>'2.00'),array('tsk_hours_spent'=>'0.00'),array('tsk_hours_spent'=>'0.00'),array('tsk_hours_spent'=>'0.00'));
$finalArray = array();
foreach($tsk_hours_spent as $key){
$tmp = (explode('.',$key['tsk_hours_spent']));
$finalArray['partOne'][] = $tmp[0];
$finalArray['partSecond'][] = $tmp[1];
}
echo implode(',',$finalArray['partOne']);
echo "</br>";
echo implode(',',$finalArray['partSecond']);
Try this,
$array=array(array('tsk_hours_spent' => '23425.00'),
array('tsk_hours_spent' => '2.00'),
array('tsk_hours_spent' => '0.00'),
array('tsk_hours_spent' => '0.00'),
array('tsk_hours_spent' => '0.20'));
$hour=array();
$minut=array();
foreach($array as $value)
{
$temp=explode('.', $value['tsk_hours_spent'].' ');
array_push($hour, $temp[0]);
array_push($minut, $temp[1]);
}
print_r($hour);
print_r($minut);
Output
Array
(
[0] => 23425
[1] => 2
[2] => 0
[3] => 0
[4] => 0
)
Array
(
[0] => 00
[1] => 00
[2] => 00
[3] => 00
[4] => 20
)
Works with floating point numbers as opposed to strings in answers above
$arr = array();
$arr[] = array('tsk_hours_spent'=>23425.00); //floating point numbers
$arr[] = array('tsk_hours_spent'=>2.00);
$arr[] = array('tsk_hours_spent'=>0.00);
$arr[] = array('tsk_hours_spent'=>0.00);
$arr[] = array('tsk_hours_spent'=>0.20);
$first = array();
$second = array();
foreach($arr as $k => $v){
$ex = explode('.',strval($v['tsk_hours_spent']));
$first[] = $ex[0];
$second[] = isset($ex[1])?str_pad($ex[1],2,0,STR_PAD_RIGHT):'00';
}
print_r($first);
print_r($second);
Array
(
[0] => 23425
[1] => 2
[2] => 0
[3] => 0
[4] => 0
)
Array
(
[0] => 00
[1] => 00
[2] => 00
[3] => 00
[4] => 20
)
A functional approach to this problem:
$arr1 = $arr2 = array();
array_walk($data, function(&$value) use (&$arr1, &$arr2) {
$parts = explode('.', $value['tsk_hours_spent']);
$arr1[] = $parts[0];
$arr2[] = $parts[1];
});
echo implode(',', $arr1);
echo implode(',', $arr2);
Simpler solution using foreach:
$arr1 = $arr2 = array();
foreach ($data as $arr) {
list($beforedot, $afterdot) = explode('.', $arr['tsk_hours_spent']);
$arr1[] = $beforedot;
$arr2[] = $afterdot;
}
echo implode(',', $arr1);
echo implode(',', $arr2);
Demo
Addition to #sisimaster more shorter code.
Considering $a is your required array
for ($i=0;$i<=count($a)-1;$i++){
list($whole[], $decimal[]) = explode('.', $a[$i]['tsk_hours_spent']);
}
$wholenumber=implode(",",$whole); //23425,2,0,0,0
$decimalnumber=implode(",",$decimal);//00,00,00,00,00
Related
I got string like 1_2_3_4_5 and I want an array like this:
array(
[0] = 1
[1] = 1_2
[2] = 1_2_3
[3] = 1_2_3_4
[4] = 1_2_3_4_5
)
Any idea for a oneliner?
just for fun using substr
$st = '1_2_3_4_5';
$num[]=$st;
while($pos=strrpos($st,'_')){
$num[]=$st=substr($st,0,$pos);
}sort($num);
print_r($num);
Output
(
[0] => 1
[1] => 1_2
[2] => 1_2_3
[3] => 1_2_3_4
[4] => 1_2_3_4_5
)
<?php
$input = '1_2_3_4_5';
// Get an array with 1, 2, 3, 4 and 5
$parts = explode('_', $input);
$output = [];
$i = 1;
foreach ($parts as $part) {
// array_slice() will take 1 to n elements from the array of numbers
$values = array_slice($parts, 0, $i++);
// Join the values
$output[] = implode('_', $values);
}
print_r($output);
It will show this:
Array
(
[0] => 1
[1] => 1_2
[2] => 1_2_3
[3] => 1_2_3_4
[4] => 1_2_3_4_5
)
Try it at 3V4L.
Problem
Need to find the all nearby node elements for every node on the following graph using PHP
Graph
Input String
$string_arr = array (‘c1#c2#6’, ‘c2#c3#12’, ‘c2#c4#3’, ‘c3#c5#22’, ‘c3#c6#23’, ‘c4#c7#13’, ‘c5#c8#16’, ‘c6#c8#11’, ‘c6#c9#9’, ‘c7#c9#12’, ‘c9#c10#15’, ‘c8#c10#7’);
(Use above variable as input parameter for your code. And you can treat it as string or array or array of string)
Required OUTPUT:
Please print the array showing all node elements with their nearby node.
e.g.
Array(
[c1] => Array
(
[0] => c2
)
[c2] => Array
(
[0] => c1
[1] => c3
[2] => c4
)
)
My Code
<?php
$string_arr = array('c1#c2#6', 'c2#c3#12', 'c2#c4#3', 'c3#c5#22', 'c3#c6#23', 'c4#c7#13', 'c5#c8#16', 'c6#c8#11', 'c6#c9#9',
'c7#c9#12', 'c9#c10#15', 'c8#c10#7');
foreach ($string_arr as $k => $v) {
$tmp = explode('#', $v);
$new_array[$tmp[0]][] = $tmp[1];
#$new_array2[$tmp[0]][] = $tmp[2];
}
print_r($new_array);
?>
My Output
Array (
[c1] => Array
(
[0] => c2
)
[c2] => Array
(
[0] => c3
[1] => c4
)
[c3] => Array
(
[0] => c5
[1] => c6
)
[c4] => Array
(
[0] => c7
)
[c5] => Array
(
[0] => c8
)
[c6] => Array
(
[0] => c8
[1] => c9
)
[c7] => Array
(
[0] => c9
)
[c9] => Array
(
[0] => c10
)
[c8] => Array
(
[0] => c10
)
)
I think all you need to do is also add the items in the other way round, so you currently add...
$new_array[$tmp[0]][] = $tmp[1];
so also add with the values swapped
$new_array[$tmp[1]][] = $tmp[0];
To give...
foreach ($string_arr as $k => $v) {
$tmp = explode('#', $v);
$new_array[$tmp[0]][] = $tmp[1];
$new_array[$tmp[1]][] = $tmp[0];
}
<?php
$string_arr = array ('c1#c2#6', 'c2#c3#12', 'c2#c4#3', 'c3#c5#22', 'c3#c6#23', 'c4#c7#13', 'c5#c8#16', 'c6#c8#11', 'c6#c9#9', 'c7#c9#12', 'c9#c10#15', 'c8#c10#7');
$simplifyArr = array();
foreach ($string_arr as $key => $value) {
$simplifyArr[] = getnode($value);
}
$keysArr = array_unique(array_column($simplifyArr, 'parent'));
$outputArr = array();
foreach ($keysArr as $key) {
foreach ($simplifyArr as $value) {
if($value['parent'] == $key){
$outputArr[$key][] = $value['child'];
}
if($value['child'] == $key){
$outputArr[$key][] = $value['parent'];
}
}
}
echo "<pre>";
print_r($outputArr);
echo "</pre>";
function getnode($string)
{
$extract = explode('#', $string);
$arr['parent'] = $extract[0];
$arr['child'] = $extract[1];
$arr['weight'] = $extract[2];
return $arr;
}
?>
I have this type of Array
Array
(
[0] => Samy Jeremiah,55
[1] => Nelson Owen,93
[2] => McMaster Ashlie,88
[3] => Marsh Harlow,97
[4] => Macfarquhar Aiden,95
[5] => Lowe Sophie,91
);
I need to convert this array into following type of json
data: [
['Samy Jeremiah',55 ],
['Nelson Owen',93 ],
['McMaster Ashlie',88 ] ,
['Marsh Harlow',97 ] ,
['Macfarquhar Aiden',95 ],
['Lowe Sophie',91 ]
]
Try this
<?php
$yourArray = array(
'0' => 'Samy Jeremiah,55',
'1' => 'Nelson Owen,93',
'2' => 'McMaster Ashlie,88',
'3' => 'Marsh Harlow,97',
'4' => 'Macfarquhar Aiden,95',
'5' => 'Lowe Sophie,91',
);
#Check output 01
//print_r($yourArray);
foreach ($yourArray as $value) {
$explodeValue = explode( ',', $value );
$newName []= array($explodeValue[0] => $explodeValue[1]);
}
#Check output 02
//print_r($newName);
#Check output 03
echo(json_encode($newName));
?>
PHPFiddle Preview
Output 01
Array (
[0] => Samy Jeremiah,55
[1] => Nelson Owen,93
[2] => McMaster Ashlie,88
[3] => Marsh Harlow,97
[4] => Macfarquhar Aiden,95
[5] => Lowe Sophie,91
)
Output 02
Array (
[0] => Array ( [Samy Jeremiah] => 55 )
[1] => Array ( [Nelson Owen] => 93 )
[2] => Array ( [McMaster Ashlie] => 88 )
[3] => Array ( [Marsh Harlow] => 97 )
[4] => Array ( [Macfarquhar Aiden] => 95 )
[5] => Array ( [Lowe Sophie] => 91 )
)
Output 03
[
{"Samy Jeremiah":"55"},
{"Nelson Owen":"93"},
{"McMaster Ashlie":"88"},
{"Marsh Harlow":"97"},
{"Macfarquhar Aiden":"95"},
{"Lowe Sophie":"91"}
]
Your desired result is an array of arrays. You have to split each entry of your array into 2 entities and push them as an array into a new array, then json_encode() the new array.
This php-snippet only works, if your input is consistantly an array of strings, containing each one comma as separator between name and int-value:
$arr2 = array();
foreach($arr1 as $e) {
list($name, $val) = explode(',', $e);
$arr2[] = array($name, (int)$val);
}
echo json_encode($arr2);
Use below code
$data = array('Samy Jeremiah,55', 'Nelson Owen,93', 'McMaster Ashlie,88', 'Marsh Harlow,97', 'Macfarquhar Aiden,95', 'Lowe Sophie,91');
$res = array();
foreach($data as $e) {
$list = explode(',', $e);
$res[] = array($list[0], $list[1]);
}
echo json_encode(['data'=>$arr2]);
Output
{"data":[
["Samy Jeremiah",55],
["Nelson Owen",93],
["McMaster Ashlie",88],
["Marsh Harlow",97],
["Macfarquhar Aiden",95],
["Lowe Sophie",91]
]
}
Using the json_encode you can achieve what you want.
Suppose your array name is $arr, so now apply the json_encode.
echo json_encode(array('data'=>$arr)); //your json will be print here
Real time Example:
$arr = array('Samy Jeremiah,55', 'Nelson Owen,93', 'McMaster Ashlie,88', 'Marsh Harlow,97', 'Macfarquhar Aiden,95', 'Lowe Sophie,91');
$new_arr = array();
foreach($arr as $k => $val){
$na = explode(",", $val);
$na[0] = "'".$na[0]."'";
$value = implode(",", $na);
$new_arr[$k] = $value;
}
echo json_encode(array("data" => $new_arr));
This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 9 months ago.
I have the following array
Array (
[0] => Array
(
[0] => ALFA
[1] => 213
)
[1] => Array
(
[0] => ALFA
[1] => 151
)
[2] => Array
(
[0] => ALFA
[1] => 197
)
[3] => Array
(
[0] => BETA
[1] => 167
)
[4] => Array
(
[0] => ZETA
[1] => 254
)
[5] => Array
(
[0] => GAMA
[1] => 138
)
[6] => Array
(
[0] => GAMA
[1] => 213
)
)
And I would like to group the key[0] of the subarray so I can see how many equal keys it has.
Something like that:
ALFA => 3
BETA => 1
EPSI => 1
GAMA => 2
I tried with array_count_values, but without success.
foreach ($array as $value) {
echo '<pre>';
print_r(array_count_values($value));
echo '</pre>';
}
With that we have following result:
Array
(
[ALFA] => 1
[213] => 1
)
Array
(
[ALFA] => 1
[151] => 1
)
...
Array
(
[GAMA] => 1
[213] => 1
)
And after that I would like to sum the values of each group as well.
ALFA => 213 + 151 + 197
BETA => 167
ZETA => 254
GAMA => 138 + 213
I think that when we solve the first part of the problem, the second would follow easier with quite the same method.
The final purpose is to divide the sum of values by the number of occurrences of each key group, so we can have an average of the values just like that:
ALFA => (213+151+197) / 3 = 187
BETA => 167
ZETA => 254
GAMA => (138+213) / 2 = 175,5
This is not the main problem, but as I said, I'm stuck with the beginning of the solution and would appreciate any help.
I'm surprised at all the long and complicated answers. However, the initial foreach to model your data to something manageable is needed. After that you just need to do a really simple array_walk.
<?php
$result = array();
foreach ($array as $el) {
if (!array_key_exists($el[0], $result)) {
$result[$el[0]] = array();
}
$result[$el[0]][] = $el[1];
}
array_walk($result, create_function('&$v,$k', '$v = array_sum($v) / count($v);'));
?>
Result:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Solution for you is here:
Code:
$input = [
['alfa', 123],
['alfa', 223],
['alfa', 122],
['alfa', 554],
['alfa', 34],
['dalfa', 123],
['halfa', 223],
['dalfa', 122],
['halfa', 554],
['ralfa', 34]
];
$result = [];
foreach ($input as $node) {
if (isset($result[$node[0]])) {
$result[$node[0]] = ['sum' => $result[$node[0]]['sum'] + $node[1], 'count' => $result[$node[0]]['count'] + 1];
} else {
$result[$node[0]] = ['sum' => $node[1], 'count' => 1];
}
}
print_r($result);
foreach ($result as $key => &$data) {
$data = $data['sum'] / $data['count'];
}
print_r($result);
Output:
Array
(
[alfa] => Array
(
[sum] => 1056
[count] => 5
)
[dalfa] => Array
(
[sum] => 245
[count] => 2
)
[halfa] => Array
(
[sum] => 777
[count] => 2
)
[ralfa] => Array
(
[sum] => 34
[count] => 1
)
)
Array
(
[alfa] => 211.2
[dalfa] => 122.5
[halfa] => 388.5
[ralfa] => 34
)
$sort = array();
foreach ($array as $value) {
$sort[$value[0]][] = $value[1];
}
then you count how many keys each has
$keys = array();
foreach($sort as $k => $v) {
$keys[$k] = count($v);
}
then for calculating the amount
$sum = array();
$average = array();
foreach($sort as $k => $v) {
$amount = 0;
foreach($v as $val) {
$amount += $val;
}
$sum[$k] = $amount;
$average[$k] = $amount / $keys[$k];
}
HOWEVER, If you want all the details in one array:
$final = array();
foreach ($array as $value) {
$final[$value[0]]["values"][] = $value[1];
}
foreach($final as $k => $v) {
$final[$k]["amount"] = count($v['values']);
$amount = 0;
foreach($v['values'] as $val) {
$amount += $val;
}
$final[$k]["sum"] = $amount;
$final[$k]["average"] = $amount / $final[$k]["amount"];
}
example: http://jdl-enterprises.co.uk/sof/25789697.php
Includes Output
Just copy the codes to your favorite text editor, sure it works perfectly.
$items = [
['ALFA',213],
['ALFA',151],
['ALFA',197],
['BETA',167],
['ZETA',254],
['GAMA',138],
['GAMA',213]
];
echo '<pre>' . print_r($items,true) . '</pre>';
$result;
foreach ($items as $value) {
# code...
if (isset($result[$value[0]])) {
$sum = $result[$value[0]]['sum'] + $value[1];
$count = $result[$value[0]]['count'] + 1;
$result[$value[0]] = ['sum' => $sum , 'count' => $count, 'divided' => ($sum / $count)];
} else {
$result[$value[0]] = ['sum' => $value[1] , 'count' => 1 , 'divided' => ($value[1] / 1) ];
}
}
echo '<pre>' . print_r($result,true) . '</pre>';
$myArray = [
["ALFA",213],
["ALFA",151],
["ALFA",197],
["BETA",167],
["ZETA",254],
["GAMA",138],
["GAMA",213]
];
$a1 = array(); //TEMPORARY ARRAY FOR KEEPING COUNT & TOTAL VALUES
$res = array(); //ARRAY USED TO KEEP RESULT
foreach($myArray as $val)
{
//AVOID PESKY NOTICES FOR UNDEFINED INDEXES
if ( !array_key_exists($val[0],$a1) ) {
$a1[$val[0]] = array("count" => 0,"total" => 0);
$res[$val[0]] = 0;
}
//INCREMENT THE COUNT OF INSTANCES OF THIS KEY
$a1[$val[0]]["count"]++;
//INCREMENT THE TOTAL VALUE OF INSTANCES OF THIS KEY
$a1[$val[0]]["total"]+=$val[1];
// UPDATE RESULT ARRAY
$res[$val[0]] = $a1[$val[0]]["total"] / $a1[$val[0]]["count"];
}
print_r($res);
Should result in:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Sample: http://phpfiddle.org/lite/code/a7nt-5svf
I have two array and I need to merge it together !!
Array 1
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2014] => 136476
)
[1] => Array
(
[brand] => TIFFANY & CO.
[amount_2014] => 22000
)
[2] => Array
(
[brand] => Test
[amount_2014] => 33000
)
)
Array 2
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2013] => 22052
)
[1] => Array
(
[brand] => Test
[amount_2013] => 3313
)
)
I need the result array as:
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2014] => 136476
[amount_2013] => 22052
)
[1] => Array
(
[brand] => TIFFANY & CO.
[amount_2014] => 22000
[amount_2013] => 0
)
[2] => Array
(
[brand] => Test
[amount_2014] => 33000
[amount_2013] => 3313
)
)
So for every [brand] I need the amount in [amount_2014] & [amount_2013], if any one is not present then I need it value as 0;
I am using CodeIgniter for this project, I have only one table with field (brand, amount, year) am issuing two queries for getting sum of amount for 2013 & 2014.
(I am fighting with array_merge and array_combine but no use for me in this case, if any one can help with query then it's also very much helpful).
Try this:
function cars_array_merge()
{
$arrays = func_get_args();
foreach ($arrays as &$array)
{
$new_arr = array();
foreach ($array as $value)
{
$brand = $value['brand'];
unset($value['brand']);
$new_arr[$brand] = $value;
}
$array = $new_arr;
}
$arrays = call_user_func_array('array_merge_recursive', $arrays);
foreach ($arrays as $brand => &$array)
$array['brand'] = $brand;
return array_values($arrays);
}
// testing
$arr1 = [
[ 'brand' => 'CARTIER', 'mount_2014' => 136476 ],
[ 'brand' => 'TIFFANY & CO.', 'mount_2014' => 22000 ]
];
$arr2 = [
[ 'brand' => 'CARTIER', 'mount_2013' => 22052 ]
];
print_r(cars_array_merge($arr1, $arr2));
Output:
Array
(
[0] => Array
(
[mount_2014] => 136476
[mount_2013] => 22052
[brand] => CARTIER
)
[1] => Array
(
[mount_2014] => 22000
[brand] => TIFFANY & CO.
)
)
<?php
for ($i = 0, $max = count($arr1); $i < $max; ++$i) {
$arr1[$i]['amount_2013'] = isset($arr2[$i]['amount_2013']) ? $arr2[$i]['amount_2013'] : 0;
}
$merge = array_merge($arr1, $arr2);
$temp = $merge;
$newArr = array(); $key_array = array();
foreach($merge as $key=>$val){
$b = $val['brand'];
$a1 = isset($val['amount_2013']) ? $val['amount_2013'] : 0;
$a2 = isset($val['amount_2014']) ? $val['amount_2014'] : 0;
unset($temp[$key]);
foreach($temp as $k=>$values){
if($values['brand'] == $b){
if($a1 == 0){
$a1 = isset($values['amount_2013']) ? $values['amount_2013'] : 0;
}
if($a2 == 0){
$a2 = isset($values['amount_2014']) ? $values['amount_2014'] : 0;
}
unset($temp[$k]);
}
}
if(!in_array($b, $key_array))
{
$newArr[] = array('brand' => $b, 'amount_2014' => $a2, 'amount_2013' => $a1);
}
$key_array[] = $b;
}
print_r($newArr);
This is what I used:
<?php
$arr1 = array(0=>array("brand"=>"CARTIER","amount_2014"=>136476), 1=>array("brand"=>"tiffany","amount_2014"=>22000));
$arr2 = array(0=>array("brand"=>"CARTIER","amount_2013"=>22000));
foreach ($arr2 as $key=>$value){
if( $value["brand"] == "CARTIER")
{
$arr1[0]["amount_2013"] = $value["amount_2013"];
$arr1[1]["amount_2013"] = 0;
}
else
{
$arr1[1]["amount_2013"] = $value["amount_2013"];
$arr1[0]["amount_2013"] = 0;
}
}
print_r($arr1);
?>