I have this code:
$rows = array();
$table = array();
foreach($kol as $r) {
$temp = array();
// the following line will be used to slice the Pie chart
$m = array('label' => (string) $r['naziv'], 'type' => 'string');
$rows[] = ($m);
}
$table['cols'] = $rows;
and I get this json:
{"cols":[{"label":"Pera Peric","type":"string"},{"label":"IMT 510-td","type":"string"},{"label":"Laza Lazic","type":"string"}
How I can put data on $m array to position 0 to get json like this:
{"cols":[{"label":"Datum,"type":"Date"},{"label":"Pera Peric","type":"string"},{"label":"IMT 510-td","type":"string"},{"label":"Laza Lazic","type":"string"}
so here I just want to add this data: {"label":"Datum,"type":"Date"} to array ...
Just add it before you start your loop (I cleaned a bit):
$rows = array();
$table = array();
$rows[] = array('label' => 'Datum', 'type' => 'Date')
foreach ($kol as $r) {
$rows[] = array('label' => (string) $r['naziv'], 'type' => 'string');
}
$table['cols'] = $rows;
array_unshift()
<?php
// your json
$json = '{"cols":[{"label":"Pera Peric","type":"string"},{"label":"IMT 510-td","type":"string"},{"label":"Laza Lazic","type":"string"}]}';
// json array to php array using json_decode()
$json_decode = json_decode($json, true);
// your $m php array
$m = array(
'label' => 'Datum',
'type' => 'Date'
);
// add you $m to position 0 in index 'cols'
array_unshift($json_decode['cols'], $m);
Done!
array(1) {
["cols"]=>
array(4) {
[0]=>
array(2) {
["label"]=>
string(5) "Datum"
["type"]=>
string(4) "Date"
}
[1]=>
array(2) {
["label"]=>
string(10) "Pera Peric"
["type"]=>
string(6) "string"
}
[2]=>
array(2) {
["label"]=>
string(10) "IMT 510-td"
["type"]=>
string(6) "string"
}
[3]=>
array(2) {
["label"]=>
string(10) "Laza Lazic"
["type"]=>
string(6) "string"
}
}
}
Back to json (if you want)
$json = json_encode($json_decode);
Related
I have an array like this
array(2) {
["sys_ID"]=> string(32) "ab0ce921dba8a810f6db3892399619d9" ["sites"]=> array(5) {
[0]=> array(2) {
["sys_ID"]=> string(32) "448ce5a1dba8a810f6db3892399619ba" ["service"]=> string(4) "IDMB" } [1]=> array(2) {
["sys_ID"]=> string(32) "448ce5a1dba8a810f6db3892399619ba" ["service"]=> string(4) "ODMB" } [2]=> array(2) {
["sys_ID"]=> string(32) "598ce5a1dba8a810f6db3892399619bc" ["service"]=> string(4) "IDMB" } [3]=> array(2) {
["sys_ID"]=> string(32) "876ce5a1dba8a810f6db38923996199f" ["service"]=> string(4) "IDMB" } [4]=> array(2) {
["sys_ID"]=> string(32) "876ce5a1dba8a810f6db38923996199f" ["service"]=> string(4) "ODMB" } } }
If there is a duplicate ['sys_ID'] I want to change the first ['service'] => "IDMB,ODMB" then delete the duplicate value so there is only 1. So the above would become
array(2) {
["sys_ID"]=> string(32) "ab0ce921dba8a810f6db3892399619d9" ["sites"]=> array(5) {
[0]=> array(2) {
["sys_ID"]=> string(32) "448ce5a1dba8a810f6db3892399619ba" ["service"]=> string(4) "IDMB,ODMB" } [1]=> array(2) {
["sys_ID"]=> string(32) "598ce5a1dba8a810f6db3892399619bc" ["service"]=> string(4) "IDMB" } [2]=> array(2) {
["sys_ID"]=> string(32) "876ce5a1dba8a810f6db38923996199f" ["service"]=> string(4) "IDMB,ODMB" } ]} }
The first array was made getting POST values;
<?php
foreach ($_POST['services'] as $item) {
$parts = explode(',', $item);
$siteID = $parts[1];
$services = $parts[0];
$data['sites'][] = [
'sys_ID' => $siteID,
'service' => $services
];
}
?>
Change the way you generate your array to something like this:
<?php
$data = [
'sites' => [],
];
foreach ($_POST['services'] as $item) {
// Gather your data
$parts = explode(',', $item);
$siteID = $parts[1];
$services = $parts[0];
// Set flag to remember whether you need to add it
$add = true;
// Loop through existing data and check if the sys_ID already exists
foreach ($data['sites'] as &$dataDetails) {
// It does ... so just append your service
if ($dataDetails['sys_ID'] === $siteID) {
$add = false;
$dataDetails['service'] .= ',' . $services;
break;
}
}
// Couldn't find the sys_ID => Add new entry
if ($add) {
$data['sites'][] = [
'sys_ID' => $siteID,
'service' => $services
];
}
}
?>
It will be better to fill the array properly from the beginning; however I will still post a solution. We have the array defined like this:
$arr = array(
'sys_ID' => 'ab0ce921dba8a810f6db3892399619d9',
'sites' => array(
0 => array(
'sys_ID' => "448ce5a1dba8a810f6db3892399619ba",
'service'=> "IDMB"
),
1 => array(
'sys_ID' => "448ce5a1dba8a810f6db3892399619ba",
'service'=> "ODMB"
),
2 => array(
'sys_ID'=> "598ce5a1dba8a810f6db3892399619bc",
'service'=> "IDMB"
),
3 => array(
'sys_ID'=> "876ce5a1dba8a810f6db38923996199f",
'service'=> "IDMB"
),
4 => array(
'sys_ID'=> "876ce5a1dba8a810f6db38923996199f",
'service'=> "ODMB"
)
)
);
To merge the elements like described, you can do the following loop:
// For each site (1)...
for($i=0; $i<count($arr["sites"])-1; $i++){
// Take each of sites starting from the next one to the end (2)
for($j=$i+1; $j<count($arr["sites"]); $j++){
// If there is a match in sys_ID beteen (1) and (2)
if($arr["sites"][$i]['sys_ID'] == $arr["sites"][$j]['sys_ID']){
// Merge the service into (1) with comma separation
$arr["sites"][$i]['service'] = $arr["sites"][$i]['service'].",".$arr["sites"][$j]['service'];
// then delete (2)
array_splice($arr["sites"],$j,1);
$j--;
}
}
}
Note that this will reindex the numebers (1,2,3...). If you wish to preserve them, you can use unset() instead.
i create function who return normal array :
function get_list_array () {
$list_object = get_list_objects();
foreach ( $list_object as $every_object) {
$list_array[] = array (
"wprm_$every_object->name" => array (
'name' => _x("$every_object->label", , 'test'),
'singular_name' => _x("$every_object->name", , 'test'),));
}
return $list_array ;
}
var_dump ($list_array);
array(2) {
[0]=> array(1) { ["object_1"]=> array(2) {
["name"]=> string(10)
"name_object1" ["singular_name"]=> string(15) "singular_name_object1" } }
[1]=> array(1) { ["object_2"]=> array(2) {
["name"]=> string(4)
"name_object2" ["singular_name"]=> string(10) "singular_name2" } } }
And i want the get in place just the associative array like this:
array ("object_1" => array (["name"]=> string(10) "name_object1"
["singular_name"]=> string(15) "singular_name_object1" } ,
"object_2" => array(2) {
["name"]=> string(4)
"name_object2" ["singular_name"]=> string(10) "singular_name2" } } }
any idea how i can modify my function in order the get the second output.
You're wrapping the array you actually want into another array by doing this:
$list_array[] = array(
"wprm_$every_object->name" => array(
Instead, you should simply assign the new array to $list_array directly:
$list_array["wprm_$every_object->name"] = array(
Also, please think about how you indent your code, because wow. Your function could look like this:
function get_list_array () {
$list_object = get_list_objects();
foreach ($list_object as $every_object) {
$list_array["wprm_$every_object->name"] = array(
'name' => _x("$every_object->label", , 'test'),
'singular_name' => _x("$every_object->name", , 'test'),
);
}
return $list_array;
}
I've got this array, and I want to loop through it and add up the values prices that are on the same OrderDate. The other values like the Discount code I want to add as a sub-array.
array(3) {
[0]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
NULL
["TotalRevenue"]=>
string(9) "147618.76"
["Discount_Revenue"]=>
string(8) "13453.77"
}
[1]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
string(6) "SALE38"
["TotalRevenue"]=>
string(8) "364.92"
["Discount_Revenue"]=>
string(8) "4083.64"
}
[2]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
string(9) "WELCOME20"
["TotalRevenue"]=>
string(6) "113.83"
["Discount_Revenue"]=>
string(6) "113.83"
}
}
So it should then look like:
array(3) {
[0]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCodes"]=> array {
[0] => "DISCOUNT"
[1] => "SALE38"
[2] => "WELCOME20"
)
["TotalRevenue"]=>
string(9) "147618.76"
["Discount_Revenue"]=>
string(8) "13453.77"
}
}
I believe I have fixed it using this loop adding to the array if the key exists. Not sure if this is the most efficient way to do it though?
foreach ($results as $k => $result){
if( array_key_exists($result['OrderDate'], $arr)){
$arr[$result['OrderDate']]['price'] += $result['TotalRevenue'];
$arr[$result['OrderDate']]['new'] = false;
} else {
$arr[$result['OrderDate']] = array(
'price' => $result['TotalRevenue'],
'new' => true
);
}
}
I've come to my own solution if anyone else needs it.
$arr = array();
foreach ($results as $k => $result){
if( array_key_exists($result['OrderDate'], $arr)){
$arr[$result['OrderDate']]['Total_Revenue'] += $result['TotalRevenue'];
$arr[$result['OrderDate']]['Discount_Revenue'] += $result['Discount_Revenue'];
isset($result['DiscountCode']) ? $arr[$result['OrderDate']]['Discount_Code'][] = $result['DiscountCode'] : '';
$arr[$result['OrderDate']]['new'] = false;
} else {
$arr[$result['OrderDate']] = array(
'Total_Revenue' => $result['TotalRevenue'],
'Discount_Revenue' => $result['Discount_Revenue'],
'new' => true
);
isset($result['DiscountCode']) ? $arr[$result['OrderDate']]['Discount_Code'][] = $result['DiscountCode'] : '';
}
}
["trnx_date"]=>
array(2) {
[0]=>
string(10) "2017-01-10"
[1]=>
string(10) "2017-01-10"
}
["curr_from"]=>
array(2) {
[0]=>
string(3) "USD"
[1]=>
string(3) "PHP"
}
["curr_from_amt"]=>
array(2) {
[0]=>
string(8) "4,000.00"
[1]=>
string(8) "3,000.00"
}
["curr_to"]=>
array(2) {
[0]=>
string(3) "GBP"
[1]=>
string(3) "SAR"
}
["curr_to_amt"]=>
array(2) {
[0]=>
string(8) "3,000.00"
[1]=>
string(8) "2,000.00"
}
["amount"]=>
array(2) {
[0]=>
string(8) "7,000.00"
[1]=>
string(8) "5,000.00"
}
I have the above array which was being submitted. This input was in sets of multiple field which was generated by dynamic table row. How can I group this into 1 (one) array so that I could save in the database? Like this:
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "USD",
'curr_from_amt' => "4,000.00",
'curr_to' => "GBP",
'curr_to_amt' => "3,000.00",
'amount' => "7,000.00"
),
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "PHP",
'curr_from_amt' => "3,000.00",
'curr_to' => "SAR",
'curr_to_amt' => "2,000.00",
'amount' => "5,000.00"
),
All of the above we being populated like this:
$trnx_date = $this->input->post('trnx_date');
$curr_from = $this->input->post('curr_from');
$curr_from_amt = $this->input->post('curr_from_amt');
$curr_to = $this->input->post('curr_to');
$curr_to_amt = $this->input->post('curr_to_amt');
$amount = $this->input->post('amount');
Assuming all the sub-arrays have the same length, you can use a simple for loop that iterates over the index of one of them, and use that to access each of the sub-arrays at that index. Then combine all of them into the associative array for each customer.
$result = array();
$keys = array_keys($array);
$len = count($array[$keys[0]]); // Get the length of one of the sub-arrays
for ($i = 0; $i < $len; $i++) {
$new = array();
foreach ($keys as $k) {
$new[$k] = $array[$k][$i];
}
$result[] = $new;
}
$arr = array(
'trnx_date' => array('2017-01-10', '2017-01-10'),
'curr_from' => array('USD', 'PHP'),
'curr_from_amt' => array('4,000.00', '3,000.00'),
'curr_to' => array('GBP', 'SAR'),
'curr_to_amt' => array('3,000.00', '2,000.00'),
'amount' => array('7,000.00', '5,000.00')
);
$arr_out = array();
$arr_keys = array_keys($arr);
for($i = 0; $i < count($arr[$arr_keys[0]]); $i++) {
$new_arr = array();
foreach($arr_keys as $key => $value) {
$new_arr[$value] = $arr[$value][$i];
}
$arr_out[] = $new_arr;
}
var_dump($arr_out);
Hope it helps!
How about this?
// assume $arr is your original data array
$keys = array_keys($arr);
$result = array();
foreach($keys as $key) {
$vals = $arr[$key];
foreach($vals as $i =>$val) {
if (!is_array($result[$i]) {
$result[$i] = array();
}
$result[$i][$key] = $val;
}
}
var_dump($result);
EDIT: added array check for $result[$i]
I want to make my flat array to a nested array but I can't seem to do this ;/
the code that I tryed to make it nested with:
<?php
$link = mysqli_connect("localhost", "db_phpnav", "jeXS9ftZhmJdzRWd", "db_phpNav");
$sql = "SELECT ID, PID, Naam FROM tb_nav";
$result = mysqli_query($link, $sql);
function convertToTree(array $flat, $idField = 'ID',
$parentIdField = 'PID',
$childNodesField = 'childNodes') {
$indexed = array();
foreach ($flat as $row) {
$indexed[$row[$idField]] = $row;
$indexed[$row[$idField]][$childNodesField] = array();
}
$root = null;
foreach ($indexed as $id => $row) {
$indexed[$row[$parentIdField]][$childNodesField][$id] =& $indexed[$id];
if (!$row[$parentIdField]) {
$root = $id;
}
}
return array($root => $indexed[$root]);
}
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
convertToTree($rows);
?>
the array it gives out. it clearly doesn't do what I intended for.
array(3) {
[0]=>
array(3) {
["ID"]=>
string(1) "2"
["PID"]=>
NULL
["Naam"]=>
string(7) "Contact"
}
[1]=>
array(3) {
["ID"]=>
string(1) "5"
["PID"]=>
string(1) "2"
["Naam"]=>
string(7) "testing"
}
[2]=>
array(3) {
["ID"]=>
string(1) "6"
["PID"]=>
NULL
["Naam"]=>
string(8) "testing2"
}
}
How do i get the array to be nested nicely?
it should look more like this:
[0]=>
array(3) {
["ID"]=>
string(1) "2"
["PID"]=>
NULL
["Naam"]=>
string(7) "Contact"
'childNodes' => array(
2 => array(
["ID"]=>
string(1) "5"
["PID"]=>
string(1) "2"
["Naam"]=>
string(7) "testing"
'childNodes' => array ();
);
}
Suppose this is (kind of) what you want:
<?PHP
$entries = array();
$entries[] = array("ID" => "2", "PID" => NULL, "Naam" => "Contact");
$entries[] = array("ID" => "5", "PID" => "2", "Naam" => "testing");
$entries[] = array("ID" => "6", "PID" => NULL, "Naam" => "testing2");
function convertToTree($flat, $idField = 'ID', $parentIdField = 'PID', $childNodesField = 'childNodes', $curIdx = NULL)
{
$indexed = array();
foreach($flat as $row)
{
if ($row[$parentIdField] == $curIdx)
{
$indexed[$row[$idField]] = $row;
$indexed[$row[$idField]]["childNodes"] = convertToTree($flat, $idField, $parentIdField, $childNodesField, $row[$idField]);
}
}
return $indexed;
}
print_r($entries);
$tree = convertToTree($entries);
print_r($tree);
?>
/**
* Transform array to a nested structure.
* This gets a little complicated. Basically, we're creating a placeholder in
* $children to hold the child terms of each parent term. Then we create a
* reference to that element in the parent term. So nesting happens via magic.
*/
function arrayFlatToNested($array, $idKey = 'ID', $parentIdKey = 'PID', $childrenKey = 'childNodes'): array
{
$arrayNested = [];
$children = [];
foreach ($array as $element) {
// Create a placeholder for the object's children.
if (!isset($children[$element[$idKey]])) {
$children[$element[$idKey]] = [];
}
// Create a link to those children.
$element[$childrenKey] = &$children[$element[$idKey]];
if (!strlen($element[$parentIdKey])) {
$arrayNested[] = $element;
} else {
// Create a placeholder for the parent.
if (!isset($children[$element[$parentIdKey]])) {
$children[$element[$parentIdKey]] = [];
}
// Add this object to the parent, even if it doesn't exist yet.
$children[$element[$parentIdKey]][] = $element;
}
}
return $arrayNested;
}