I have an array with the output (print_r):
Array
(
[a] => 706
[b] => 194
[c] => 164
[d] => 44
[e] => 42
[f] => 41
[g] => 40
[h] => 38
[i] => 13
)
I need to convert it to a json of this format:
[{"name":"a","value":706},{"name":"b","value":194},{"name":"c","value":164},{"name":"d","value":44},{"name":"e","value":42},{"name":"f","value":41},{"name":"g","value":40},{"name":"h","value":38},{"name":"i","value":13}]
This is what I've tried but I'm just guessing and not getting the right output :
echo '[';
foreach($sortedArray as $key => $value) {
echo $dataTable = json_encode(array(
'name' => $key,
'value' => $value
), JSON_NUMERIC_CHECK);
};
echo ']';
$keyPair = array();
foreach($sortedArray as $key => $value) {
$keyPair[] = array('name' => $key, 'value' => $value);
}
echo json_encode($keyPair);
http://codepad.org/xApWlo7j
Try this:
$data = array(
'a' => 234, 'b' => 2343, 'c' => 23423, /* etc. */
);
$new_data = array();
foreach ($data as $k => $v) {
$new_data[] = array(
'name' => $k, 'value' => (number)$v
);
}
print json_encode($new_data);
Code
$arr = array(
'a' => 706,
'b' => 194,
'c' => 164,
'd' => 44,
'e' => 42,
'f' => 41,
'g' => 40,
'h' => 38,
'i' => 13);
$map_arr = array();
foreach ($arr as $k => $v)
$map_arr[] = array('name' => $k, 'value' => intval($v));
print json_encode($map_arr);
Result
[{"name":"a","value":706},{"name":"b","value":194},{"name":"c","value":164},
{"name":"d","value":44},{"name":"e","value":42},{"name":"f","value":41},
{"name":"g","value":40},{"name":"h","value":38},{"name":"i","value":13}]
I tried to link my example here: http://sandbox.onlinephpfunctions.com/, but the share CAPTCHA is disabled...
Related
i want to combine the values of array having same index name in foreach loop..
i tried array_combine but it returns the single array.
$data = $_POST['variable']; //it contain the values in an array
$result=array();
foreach ($data as $mycat){
$result = array_merge($result, $mycat);
}
echo "<pre>";print_r($result);echo "</pre>";
it returns only data in single array
Array
(
[vendor] => 1-Open Market
[priority] => 2
[demand_for_id] => 9
[ims_allocation_details_id] => 148
[temp_demand_id] => 1
)
as shown in attached picture item names are same, so when item names are same i want to combine the total values in foreach and insert only one record into database instead to two
enter image description here
the contents of $_POST['variable']; are
Array
(
[2] => Array
(
[vendor] => 1-Open Market
[temp_demand_id] => 6
[priority] => 1
[item_name] => BAJRA MOTI
[amount] => 1000
[demand_for_id] => 9
[ims_allocation_details_id] => 153
)
[1] => Array
(
[vendor] => 1-Open Market
[temp_demand_id] => 1
[priority] => 2
[item_name] => BAJRA MOTI
[amount] => 2500
[demand_for_id] => 9
[ims_allocation_details_id] => 148
)
)
You should replace
$result = array_merge($result, $mycat);
with
$result[] = array_merge($result, $mycat);
and it will not be single
UPDATE
$result = array();
foreach ($data as $mycat) {
if(!isset($result[$mycat['item_name']])) {
$result[$mycat['item_name']] = $mycat;
} else {
//do if needed
}
}
echo "<pre>";print_r($result);echo "</pre>";
You can create a custom function to solve your problem.
Example:
<?php
$array = [
[
'vendor' => '1-Open Market',
'temp_demand_id' => 6,
'priority' => 1,
'item_name' => 'BAJRA MOTI',
'amount' => 1000,
'demand_for_id' => 9,
'ims_allocation_details_id' => 153,
],
[
'vendor' => '1-Open Market',
'temp_demand_id' => 1,
'priority' => 2,
'item_name' => 'BAJRA MOTI',
'amount' => 2500,
'demand_for_id' => 9,
'ims_allocation_details_id' => 148,
],
[
'vendor' => '1-Open Market',
'temp_demand_id' => 5,
'priority' => 3,
'item_name' => 'BAJRA MOTI',
'amount' => 1000,
'demand_for_id' => 11,
'ims_allocation_details_id' => 200,
],
];
function array_merge_recursive_custom($array) {
$processed = null;
foreach ($array as &$subArray) {
if (empty($processed)) {
$processed = $subArray;
continue;
}
foreach ($subArray as $key => $value) {
if (is_numeric($value)) {
$subArray[$key] += $processed[$key];
}
}
$processed = $subArray;
}
return end($array);
}
var_dump(array_merge_recursive_custom($array));
I am trying to convert an input to an array which i need to us to display a Google Chart
The input array I got looks like,
$inputArray = [
['date' => '2016-12-10', 'code' => 'P'],
['date' => '2016-12-15', 'code' => 'P'],
['date' => '2017-02-10', 'code' => 'P'],
['date' => '2017-02-14', 'code' => 'P'],
['date' => '2017-03-10', 'code' => 'P'],
['date' => '2017-03-05', 'code' => 'U'],
['date' => '2017-03-11', 'code' => 'U'],
['date' => '2017-03-12', 'code' => 'P'],
['date' => '2017-04-07', 'code' => 'T'],
['date' => '2017-04-18', 'code' => 'P'],
['date' => '2017-04-19', 'code' => 'T'],
['date' => '2017-07-10', 'code' => 'P'],
];
Now I need to group by year and month and sum the code value (4 different values). For these I use a loop like so
function readPerMonth($tmpArray) {
if (empty($tmpArray)) {
$output[$year][$month] = ['P' => 0, 'T' => 0, 'U' => 0, 'E' => 0];
} else {
$output = [];
foreach ($tmpArray as $value) {
$year = date('Y', strtotime($value['date']));
$month = date('M', strtotime($value['date']));
if (empty($output[$year][$month]))
$output[$year][$month] = ['P' => 0, 'T' => 0, 'U' => 0, 'E' => 0];
// Check for incident intensity
$output[$year][$month][$value['code']] += 1;
}
}
ksort($output);
ksort($output[$year][$month]);
return $output;
}
and this gives me the Following output, hence last array is in another order???
Array
(
[2017] => Array
(
[Feb] => Array
(
[P] => 11
[T] => 0
[U] => 0
[E] => 0
)
[Mar] => Array
(
[P] => 20
[T] => 0
[U] => 0
[E] => 0
)
[Apr] => Array
(
[P] => 12
[T] => 0
[U] => 0
[E] => 0
)
[May] => Array
(
[P] => 21
[T] => 0
[U] => 0
[E] => 0
)
[Jun] => Array
(
[E] => 0
[P] => 7
[T] => 0
[U] => 1
)
)
)
and I this is an input Array which i need to convert in this JS to plot a stacked Google chart
$output = [
['2016-dec', 2, 0, 0, 0,'2'],
['2017-feb', 2, 0, 0, 0, '2'],
['2017-mar', 2, 0, 2, 0,'4'],
['2017-apr', 1, 1, 0, 0,'2'],
['2017-may', 1, 0, 0, 0, '1'],
];
My php function looks like this
function phpToJS($inputPHP) {
$return = '';
foreach ($inputPHP as $year => $months) {
foreach ($months as $monthValue => $codeValues) {
$sum = 0;
$return .= "['" . $year . " - " . $monthValue . "', ";
foreach ($codeValues as $key => $code) {
if ($key == '') {
$return .= $code;
} else {
$return .= $code . ',';
}
$sum += $code;
}
$return .= ",'" . $sum . "'],";
}
}
return $return;
}
$tmpArr = readPerMonth($inputArray);
$output = phpToJS($tmpArr);
but because of the last Array which isn't in the right order the Google Chart displays wrong.
ps: so sorry to have hit send and not finishing my question title :/
I want to remove duplicates where either measurement or altunit matches another array, but ignoring if they're blank.
Array
(
[0] => Array
(
[id] => 2
[altunit] => %
[measurement] =>
)
[1] => Array
(
[id] => 3
[altunit] =>
[measurement] => 6
)
[2] => Array
(
[id] => 4
[altunit] => %
[measurement] =>
)
[3] => Array
(
[id] => 5
[altunit] =>
[measurement] => 6
)
[4] => Array
(
[id] => 6
[altunit] =>
[measurement] => 6
)
)
Becomes
Array
(
[0] => Array
(
[id] => 2
[altunit] => %
[measurement] =>
)
[1] => Array
(
[id] => 3
[altunit] =>
[measurement] => 6
)
)
Best I can come up with is:
$test = array ( 0 => array ( 'id' => '2', 'altunit' => '%', 'measurement' => NULL, ), 1 => array ( 'id' => '3', 'altunit' => NULL, 'measurement' => '6', ), 2 => array ( 'id' => '4', 'altunit' => NULL, 'measurement' => '6', ), 3 => array ( 'id' => '5', 'altunit' => NULL, 'measurement' => '6', ), 4 => array ( 'id' => '6', 'altunit' => NULL, 'measurement' => '6', ), );
$num = [];
foreach($test as $k => $v) $num[] = $v['measurement'];
But this only works for measurement, and removes the id and altunit keys.
Humm,
Make an array of 'knowed value' for measurement and altunit and then check it it exist on the rest of the values.
something like:
$knowed_altunit=array();
$knowed_measurement=array();
foreach($test as $k=>$v){
if(in_array($v['altunit'],$knowed_altunit)
|| in_array($v['mesurement'],$knowed_measurement)){
//if the value of altunit or measurement is already knowed then remove the entry from the array,
unset($test[$k]);
}else{
//if it never been seen, add it so further entry can be checked agaisnt the knowed value
$knowed_altunit[]=$v['altunit'];
$knowed_measurement[]=$v['mesurement'];
}
}
Sorry if any typo but thins might help you wrap your head around the solution to your problem.
You can try this code:
<?php
/* before you need to check that $test variable is declarated and have all items to check */
$values_altunit = array();
$values_measurement = array();
$result = array();
foreach($test as $key => $value) {
/* check if exist altunit and measurement values in blacklist arrays */
if (!in_array($value['altunit'], $values_altunit) && !in_array($value['measurement'], $values_measurement)) {
/* if not exist, add the item to $result array */
$result[$key] = $value;
/* and add altunit and measurement values to blacklist arrays */
$values_altunit[] = $value['altunit'];
$values_measurement[] = $value['measurement'];
}
}
/* print result items */
var_dump($result);
?>
This is a short code that can give the result for unique measurements
<?php
$arr = array(
"0"=> array (
"id" => 2,
"altunit" => "%",
"measurement" => "",
),
"1"=> array (
"id" => 3,
"altunit" => "",
"measurement" => 6,
),
"2"=> array (
"id" => 4,
"altunit" => "%",
"measurement" => "",
),
"3"=> array (
"id" => 5,
"altunit" => "",
"measurement" => 6,
),
"4"=> array (
"id" => 6,
"altunit" => "",
"measurement" => 6,
)
);
$unique_measure = $new_array = array();
foreach($arr as $sup_key => $sup_val){
foreach($sup_val as $sub_key => $sub_val){
if(!in_array($sup_val['measurement'], $unique_measure)){
array_push($unique_measure, $sup_val['measurement']);
array_push($new_array,$sup_val);
}
}
}
print_r($new_array);
?>
Output :
Array
(
[0] => Array
(
[id] => 2
[altunit] => %
[measurement] =>
)
[1] => Array
(
[id] => 3
[altunit] =>
[measurement] => 6
)
)
try this code. it may do the trick.
One More approach to your problems solution can be removing that particular key from the main array using unset(your_array_key) will do the trick in the same code.
Try, this may help you
function remove_dup($array, $keys )
{
$out = array();
foreach($array as $sub)
{
if(empty($out))
{
$out[] = $sub;
continue;
}
foreach($keys as $key)
{
if($flag=in_array( $sub[$key],array_map(function($e) use($key){ return $e[$key];}, $out)) )
break;
}
if(!$flag)
$out[] = $sub;
}
return $out;
}
// Usage
print_r( remove_dup($array, array('altunit','measurement') ) );
Test
[akshay#localhost tmp]$ cat test.php
<?php
function remove_dup($array, $keys )
{
$out = array();
foreach($array as $sub)
{
if(empty($out))
{
$out[] = $sub;
continue;
}
foreach($keys as $key)
{
if($flag=in_array( $sub[$key],array_map(function($e) use($key){ return $e[$key];}, $out)) )
break;
}
if(!$flag)
$out[] = $sub;
}
return $out;
}
$array = array(
"0"=> array (
"id" => 2,
"altunit" => "%",
"measurement" => "",
),
"1"=> array (
"id" => 3,
"altunit" => "",
"measurement" => 6,
),
"2"=> array (
"id" => 4,
"altunit" => "%",
"measurement" => "",
),
"3"=> array (
"id" => 5,
"altunit" => "",
"measurement" => 4,
),
"4"=> array (
"id" => 6,
"altunit" => "",
"measurement" => 6,
)
);
print_r( remove_dup($array, array('altunit','measurement') ) );
?>
Output
[akshay#localhost tmp]$ php test.php
Array
(
[0] => Array
(
[id] => 2
[altunit] => %
[measurement] =>
)
[1] => Array
(
[id] => 3
[altunit] =>
[measurement] => 6
)
)
What you really want is a set, not an array. So if you can't fix the way you're building the array in the first place (my guess is this came from an SQL query, which would be a lot less code to rectify) you have two options for creating mapped sets in PHP.
You could use SplObjectStorage
You could use an Array with the key as a serialized representation of the set
The first approach would look something like this...
$set = new SplObjectStorage();
$arr = [
0 => [
'id' => '2',
'altunit' => '%',
'measurement' => NULL,
],
1 => [
'id' => '3',
'altunit' => NULL,
'measurement' => '6',
],
2 => [
'id' => '4',
'altunit' => NULL,
'measurement' => '6',
],
3 => [
'id' => '5',
'altunit' => NULL,
'measurement' => '6',
],
4 => [
'id' => '6',
'altunit' => NULL,
'measurement' => '6',
],
];
foreach($arr as $part) {
if (isset($part['altunit'])) { // ignore if blank
$key = (object) $part;
$set->attach($key); // attach the set
}
}
// Now you have...
foreach($set as $value) {
var_dump($value);
}
This would give you...
object(stdClass)#2 (3) {
["id"]=>
string(1) "2"
["altunit"]=>
string(1) "%"
["measurement"]=>
NULL
}
The second approach, using an array, where the array key represents a serialized version of the set would look something like this...
$set = [];
$arr = [
0 => [
'id' => '2',
'altunit' => '%',
'measurement' => NULL,
],
1 => [
'id' => '3',
'altunit' => NULL,
'measurement' => '6',
],
2 => [
'id' => '4',
'altunit' => NULL,
'measurement' => '6',
],
3 => [
'id' => '5',
'altunit' => NULL,
'measurement' => '6',
],
4 => [
'id' => '6',
'altunit' => NULL,
'measurement' => '6',
],
];
foreach($arr as $part) {
if (isset($part['altunit'])) { // ignore if blank
$key = "{$part['altunit']}\0{$part['measurement']}";
$set[$key] = $part; // attach the set
}
}
// Now you have...
foreach($set as $value) {
var_dump($value);
}
And that would give you...
array(3) {
["id"]=>
string(1) "2"
["altunit"]=>
string(1) "%"
["measurement"]=>
NULL
}
N.B
But, if this is a result set from an SQL query it's quite possible you could just more effectively eliminate the de-duplication process entirely by modifying the query to use WHERE NOT NULL and GROUP BY clauses instead.
You can try this also
<?php
$keys = array_map(function ($i) { return $i; }, $array);
$dumparr = array_combine($keys, $array);
$result = array_values($deduped);
print_r($result);
?>
This is my array:
Array (
[0] => Array ( [SocketID] => 1 [SocketName] => Name [SocketDecimal] => 0 [SocketHex] => 00 [SocketAtt] => 1 [Category] => 1 [Value] => 100 [Procentage] => 0 )
[1] => Array ( [SocketID] => 2 [SocketName] => Name2 [SocketDecimal] => 50 [SocketHex] => 32 [SocketAtt] => 1 [Category] => 1 [Value] => 800 [Procentage] => 0 )
[2] => Array ( [SocketID] => 3 [SocketName] => Name3 [SocketDecimal] => 100 [SocketHex] => 64 [SocketAtt] => 1 [Category] => 1 [Value] => 60 [Procentage] => 0 )
)
How can I extract a row by SocketDecimal?
For example: I want to extract row where SocketDecimal = 50 and make new an array only with that row.
foreach($array as $entry) {
if($entry['SocketDecimal'] == 50)
$newArr[] = $entry;
}
$newArr will contain the desired "row". Of course you can manipulate the if-statement depending on which "row" (I'd just call it array entry) you want to extract.
It's not the best way for big data! It's easy for deep multiarrays.
$arr = array(
array('socket_id'=>1,'name'=>'test1'),
array('socket_id'=>2,'name'=>'test2'),
array('socket_id'=>3,'name'=>'test3'),
array('socket_id'=>2,'name'=>'test4')
);
$newArr = array();
foreach($arr as $row){
foreach($row as $key=>$r){
if($key == 'socket_id' && $r==2)
$newArr[] = $row;
}
}
print_r($newArr);
$result = array();
foreach($input as $i){
if($i['SocketDecimal']==50)
$result[]=$i;
}
You can do it by this method
foreach ($yourarray as $key => $value){
$newarray = array("SocketDecimal"=>$value["SocketDecimal"];
}
print_r($newarray);
If your result array is like given below
$arr = array(
array( 'SocketID' => 1, 'SocketName' => 'Name', 'SocketDecimal' => 0, 'SocketHex' => 0, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 100, 'Procentage' => 0 ),
array ( 'SocketID' => 2, 'SocketName' => 'Name2', 'SocketDecimal' => 50, 'SocketHex' => 32, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 800, 'Procentage' => 0 ),
array ( 'SocketID' => 3, 'SocketName' => 'Name3', 'SocketDecimal' => 100, 'SocketHex' => 64, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 60, 'Procentage' => 0 )
);
print_r($arr);
Get row for SocketDecimal=50 by following loop:
<pre>
$resultArr = '';
foreach($arr as $recordSet)
{
if($recordSet['SocketDecimal'] == 50)
{
$resultArr[] = $recordSet;
break;
}
}
</pre>
print_r($resultArr);
break foreach loop so that it will not traverse for all the array when SocketDecimal(50) founded.
You can use array_column + array_search combo
$array = Array (
"0" => Array ( "SocketID" => 1, "SocketName" => "Name", "SocketDecimal" => 0, "SocketHex" => 00, "SocketAtt" => 1, "Category" => 1, "Value" => 100, "Procentage" => 0 ) ,
"1" => Array ( "SocketID" => 2, "SocketName" => "Name2", "SocketDecimal" => 50, "SocketHex" => 32, "SocketAtt" => 1, "Category" => 1, "Value" => 800, "Procentage" => 0 ),
"2" => Array ( "SocketID" => 3, "SocketName" => "Name3", "SocketDecimal" => 100, "SocketHex" => 64, "SocketAtt" => 1, "Category" => 1, "Value" => 60 ,"Procentage" => 0 )
);
var_dump($array[array_search(50,array_column($array,'SocketDecimal'))]);
I am new to php and i want to remove element from array Here is my array:
Array
(
[Total] => 21600000
[Items] => Array
(
[2-13] => Array
(
[Item] => 2
[PID] => 13
[UPrice] => 11000000
[Qty] => 1
[Total] => 11000000
)
[58-167] => Array
(
[Item] => 58
[PID] => 167
[UPrice] => 5300000
[Qty] => 1
[Total] => 5300000
)
)
)
And i want to remove array element by PID.
I have try this but no luck:-
$ShoppingBag =$_SESSION['ssss'];
if ($ShoppingBag !== null && $ShoppingBag['Total'] > 0) {
foreach ($ShoppingBag['Items'] as $IOrder) {
if($IOrder["PID"]==13)
{
unset($ShoppingBag[$IOrder]);
}else
{
}
}
}
Please help. Thanks
You can try with one simple array map :)
$arr = [
'Total' => 21600000,
'Items' => [
'2-13' => [
'Item' => 2,
'PID' => 13,
'UPrice' => 11000000,
'Qty' => 1,
'Total' => 11000000
],
'58-167'=> [
'Item' => 58,
'PID' => 167,
'UPrice' => 5300000,
'Qty' => 1,
'Total' => 5300000
]
]
];
$test = array_map(function($ar) {
foreach($ar as $k=>$i) {
if( isset($i['PID']) && $i['PID'] == '13')
unset($ar[$k]);
}
return $ar; } , $arr);
var_dump($test);
You need 2 loop to do the action you want.
foreach($my_array as $key=>$value)
{
if(is_array($value))
{
foreach($value as $k=>$v)
{
if($k == 'PID')
{
unset($value[$k]);
}
}
}
}
with this you can remove only element with key PID.
Hi youre unsetting the $IOrder instead of the Item that you want to delete:
This code is a solution an i tested it :
$ShoppingBag = Array
(
"Total" => 21600000,
"Items" => Array
(
"2-13" => Array
(
"Item" => 2,
"PID" => 13,
"UPrice" => 11000000,
"Qty" => 1,
"Total" => 11000000,
),
"58-167" => Array
(
"Item" => 58,
"PID" => 167,
"UPrice" => 5300000,
"Qty" => 1,
"Total" => 5300000,
),
),
);
foreach($ShoppingBag["Items"] as $key => $value){
if($value["PID"]==13){
unset($ShoppingBag["Items"][$key]);
}
}
You should know that always when you're using foreach loop the foreach( $a as $b ) when you do something to $b , $a remains the same because tey are different variables :)
Hope it will help you .
Regards.
$arr = [
'Total' => 21600000,
'Items' => [
'2-13' => [
'Item' => 2,
'PID' => 13,
'UPrice' => 11000000,
'Qty' => 1,
'Total' => 11000000
],
'58-167'=> [
'Item' => 58,
'PID' => 167,
'UPrice' => 5300000,
'Qty' => 1,
'Total' => 5300000
]
]
];
$pid_to_remove = 13;
$new_ar = array_filter(
$arr,
function ($v) using ($pid_to_remove) {
return (!isset($v['PID'])) || ($v['PID'] != $pid_to_remove);
}
);