Converting data format from array of string into numbers - php

I have
$resultArray = $sth->fetchAll(PDO::FETCH_NUM);
json_encode($resultArray,JSON_NUMERIC_CHECK);
as :
[["0.003,445.85"],...]
and I need data like this:
[[0.003,445.85],...]
When trying:
while ($row = $sth->fetch(PDO::FETCH_NUM)) {
$resultArray[] = explode(',', $row);
}
json_encode($resultArray,JSON_NUMERIC_CHECK);
I have got:
[null, null, ...]
How to achieve target?

Assuming that this your array
$resultArray = [
["0.003,445.85"],
["0.051,500.08"]
];
$result = array();
foreach($resultArray as $str) {
$inner = array();
foreach($str as $s) {
$split = explode(',',$s);
$inner = array_map('floatval',$split);
}
array_push($result,$inner);
}
echo json_encode($result,JSON_PRETTY_PRINT);
Which result to
[
[0.003,445.85],
[0.051,500.08]
]
or if your example wrong and it's
$resultArray = [["0.003","445.85"]];
json_encode with JSON_NUMERIC_CHECK will works

Related

PHP Get duplicate values in array and average second value

I have an array that looks like this:
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
I Want to find duplicate values in the first column and avarage its values from the second column.
So that this("1",3),("2",5),("2",2),("5",2),("90",1),("5",6),("2",2)
ends up like this ("1",3),("2",3),("5",4),("90",1)
Try this tested solution
I got the required Output
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
$arr1 = array_column($ratingsInPosts, 0);
$p = array_count_values($arr1);
foreach($p as $key => $value)
{
$sum = 0;
for($i=0; $i < $value; $i++)
{
$pos = array_search($key, $arr1);
$sum += $ratingsInPosts[$pos][1];
unset($arr1[$pos]);
unset($ratingsInPosts[$pos]);
}
$re[] = array('"'.$key.'"',$sum/$value);
}
print_r($re);
I hope it helps you:
$groups = array();
// in this loop we group values by first column
foreach ($ratingsInPosts as $row) {
$key = $row[0];
if (!isset($groups[$key]) {
$groups[$key] = array();
}
$groups[$key][] = $row[1];
}
$result = array();
foreach ($groups as $key => $value) {
$avg = array_sum($value) / count($value);
$row = array($key, $avg);
$result[] = $row;
}
<?php
header('Content-Type: text/plain');
$ratingsInPosts = array(array("1",3),array("2",5),array("2",2),array("5",2),array("90",1),array("5",6),array("2",2));
$result = array();
$output = array();
foreach($ratingsInPosts as $array){
$result[$array[0]][] = $array[1];
}
foreach($result as $key=>$array){
$output[] = array($key,round(array_sum($array)/count($array)));
}
var_export($output);
?>

How to add a value at the end of JSON

$resultado = mysqli_query("SELECT ...");
echo '[';
for ($i=0;$i<mysqli_num_rows($resultado);$i++) {
echo ($i > 0 ? ',' : '').json_encode(mysqli_fetch_object($resultado));
}
echo ']';
Need is Insert $SLUG the end of Json so it is the same object
{
tabela:valor
slug:valor
}
tried to array_push() but without success;
You have to encode final result, not each row:
$array = array();
for ($i=0;$i<mysqli_num_rows($resultado);$i++) {
$array[] = mysqli_fetch_object( $resultado );
}
$array[] = $SLUG; # <----------------
echo json_encode( $array );
Different approach:
$array = array();
for ($i=0;$i<mysqli_num_rows($resultado);$i++) {
$array[] = mysqli_fetch_object( $resultado );
}
$final = array( 'tabela' => $array(), 'slug' => $SLUG );
echo json_encode( $final );

how to store associative array php MySQL

I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}

php is assigning last result to all array keys

There is some problem, the code below assigning the last pr_name to all keys.
$arr = array();
while($row = mysql_fetch_array($results)) {
$keys[] = $row['pr_code'];
$items = array_fill_keys($keys, $row['pr_name']);
}
Simply with this:
$items = array();
while($row = mysql_fetch_array($results)) {
$items[$row['pr_code']] = $row['pr_name'];
}

get values on same index in PHP

I have 2D array and want to get all values which are at same index say at index '1'. what is the best way to get that as a new array.
Example: we have array(array(1,2,3), array(5,6,7)), the result must be array(2, 6).
Thanks
A simple function would do the trick:
function foobar($array, $index) {
$result = array();
foreach($array as $subarray) {
if(isset($subarray[$index])) {
$result[] = $subarray[$index];
}
}
return $result;
}
Or you can just use array_map (requires PHP 5.3):
array_map(function($array) { return $array[1]; }, $input);
$sample = array(array(1,2,3),
array(4,5,6),
array(7,8,9)
);
$index = 1;
$result = array_map(function($value) use($index) { return $value[$index]; }, $sample);
var_dump($result);
$input = array(
array(1,2,3),
array(5,6,7)
);
$output = array();
foreach ( $input as $data ) {
$output[] = $data[1];
}
$myarray=array(array(1,2,3), array(5,6,7));
$index=1;
$result=array();
foreach($myarray as $a) $result[]=$a[$index];
print_r($result);

Categories