How to Convert PHP Array to a specific JSON Output Array - php
This is my array that I wants to convert
Array
(
[0] => stdClass Object
(
[Item1] => 10/12/2021
[Item2] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
)
[1] => stdClass Object
(
[Item1] => 10/11/2021
[Item2] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
)
[2] => stdClass Object
(
[Item1] => 10/10/2021
[Item2] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
)
[3] => stdClass Object
(
[Item1] => 10/09/2021
[Item2] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
)
[4] => stdClass Object
(
[Item1] => 10/08/2021
[Item2] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
)
[5] => stdClass Object
(
[Item1] => 10/07/2021
[Item2] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
)
[6] => stdClass Object
(
[Item1] => 10/06/2021
[Item2] => Array
(
[0] => 3729195
[1] => 0
[2] => 0
[3] => 0
)
)
[7] => stdClass Object
(
[Item1] => 10/05/2021
[Item2] => Array
(
[0] => 7458390
[1] => 0
[2] => 0
[3] => 0
)
)
[8] => stdClass Object
(
[Item1] => 10/04/2021
[Item2] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
)
[9] => stdClass Object
(
[Item1] => 10/03/2021
[Item2] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
)
)
I wants this array output like this -
[{name:"", data:[0,0,0,0,0,0,3729195,7458390,0,0]},
{name:"", data:[0,0,0,0,0,0,0,0,0,0]},
{name:"", data:[0,0,0,0,0,0,0,0,0,0]},
{name:"", data:[0,0,0,0,0,0,0,0,0,0]}]
The problem is that the first element of [Item2][0] input array is the first elements of each 4 rows of data:[0] and second element of [Item2][1] is second column of each data set of data[1] elements of all 4 rows, I hope you understand what I mean.
And the dates should be in another separate list like this -
['10/12/2021', '10/11/2021', '10/10/2021', '10/09/2021', '10/08/2021', '10/07/2021', '10/06/2021', '10/05/2021', '10/04/2021', '10/03/2021'],
I have already done some tests and here is what I did so far -
$ChartDataNew = stripcslashes(trim(json_encode($jobs->charts_last10days), "\""));
$replace1 = str_replace('Item1', name, $ChartDataNew);
$replace2 = str_replace('Item2', data, $replace1);
print_r($replace2);
The above code is giving me output of an JSON object
[{"name":"10/12/2021","data":[0,0,0,0]},{"name":"10/11/2021","data":[0,0,0,0]},{"name":"10/10/2021","data":[0,0,0,0]},{"name":"10/09/2021","data":[0,0,0,0]},{"name":"10/08/2021","data":[0,0,0,0]},{"name":"10/07/2021","data":[0,0,0,0]},{"name":"10/06/2021","data":[3729195,0,0,0]},{"name":"10/05/2021","data":[7458390,0,0,0]},{"name":"10/04/2021","data":[0,0,0,0]},{"name":"10/03/2021","data":[0,0,0,0]}]
This JSON seems ok, but its not correct. First of all I wants to make the JSON output as given above without "" and name should be name:"". When you see the data in output of my json object is not matching to date in input array.
To get the list of dates I have done this and its fine -
$chartDataSeries = array();
$chartDateLabels = array();
$chartSeriesList = array();
foreach($jobs->charts_last10days as $chartData){
array_push($chartDateLabels, "'".$chartData->Item1."'");
array_push($chartDataSeries, $chartData->Item2);
}
$chartDateLabels1 = implode(', ', ($chartDateLabels));
echo ($chartDateLabels1);
Its giving me the correct output for list of dates, see
['10/12/2021', '10/11/2021', '10/10/2021', '10/09/2021', '10/08/2021', '10/07/2021', '10/06/2021', '10/05/2021', '10/04/2021', '10/03/2021']
please let me know what I am doing wrong or help me out how to do that, may be write some functions or any other way to do this.
Thanks in Advance
There's probably a more elegant solution, but the easiest way I could think of was using iterating through each element, and then constructing another array:
$resultArr = [];
// Iterate over each element of the original array
foreach ($dataArr as $key => $arr) {
// Set the date
$datesArr[$key] = $arr->Item1;
// Iterate over each element of Item2
foreach ($arr->Item2 as $i => $v) {
// Set 'data' on the resulting array item $i to the value
// using the $key from the outer loop as the index for the inner data array
$resultArr[$i]['data'][$key] = $v;
// Set the name
$resultArr[$i]['name'] = '';
}
}
// Convert from an array to JSON
echo json_encode($resultArr) . PHP_EOL;
// The dates are in $datesArr
echo json_encode($datesArr) . PHP_EOL;
$dataArr is the variable where your data is currently stored. After running this loop, $resultArr will be an array, of which each element is another array containing the data in the right format, and $datesArr is the dates from the data in their own array.
Related
how to add array value at specfic index in php codenighter
I have array value like this Array ( [0] => Array ( [channel] => 15 [id] => clsrnMdVKq2omEuQabSCHp83ezAX6w ) [1] => Array ( [channel] => 16 [id] => MfSoHUKjD5n90EZbstpiRGY7e8cgh2 ) [2] => Array ( [channel] => 17 [id] => MfSoHUKjD5n90EZbstpiRGY7e8cgh2 ) ) Now i want to add another array value in specific index .lets say i wants to add this array value at index 1 [1] => Array ( [channel] => 20 [id] => xxxxxxxxxxxewqeqwexxxxxxxewrewrw ) Now the result output should be like this Array ( [0] => Array ( [channel] => 15 [id] => clsrnMdVKq2omEuQabSCHp83ezAX6w ) [1] => Array ( [channel] => 20 [id] => xxxxxxxxxxxewqeqwexxxxxxxewrewrw ) [2] => Array ( [channel] => 16 [id] => MfSoHUKjD5n90EZbstpiRGY7e8cgh2 ) [3] => Array ( [channel] => 17 [id] => MfSoHUKjD5n90EZbstpiRGY7e8cgh2 ) ) this is my foreach loop to serlize channel and id foreach ($channel as $key => $ch) { $user_hash['channel'] = json_encode($ch); $user_hash['id'] = random_string('alnum', 30); array_push($user_hash_array, $user_hash); }
You need to split the array into 2, then insert your new value at the end of the first sub-array, then merge it with the second sub-array. EG: an array which looks like [1,3,4,5] and you want to insert "2" at position 2, then you split at position one to have [1] and [3,4,5]; then you append "2" at the end of first sub-array to form [1,2], then merge this new subarray with the other sub-array([3,4,5]) to form [1,2] + [3,4,5]. For your implementation, try this code: $array = array() // the original array you want to modify $insert = array() // the array you want to push into the original one above $position = 1 // the position at which you want to insert the new item $newArray = array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
you can use array_splice array method for add element in array at particular position <?php $original_array = array( array("channel"=>15,"id"=>"sdfdfsf1"), array("channel"=>16,"id"=>"sdfdfsf2"), array("channel"=>17,"id"=>"sdfdfsf3") ); echo "<pre>";print_r($original_array); $inserted_element = array(array("channel"=>20,"id"=>"xxxxxxxxxxewqeqwexxxxxxxewrewrw")); $position=1; array_splice( $original_array, $position, 0, $inserted_element ); echo "<pre>";print_r($original_array); ?> Output will be as following Array ( [0] => Array ( [channel] => 15 [id] => sdfdfsf1 ) [1] => Array ( [channel] => 16 [id] => sdfdfsf2 ) [2] => Array ( [channel] => 17 [id] => sdfdfsf3 ) ) Array ( [0] => Array ( [channel] => 15 [id] => sdfdfsf1 ) [1] => Array ( [channel] => 20 [id] => xxxxxxxxxxewqeqwexxxxxxxewrewrw ) [2] => Array ( [channel] => 16 [id] => sdfdfsf2 ) [3] => Array ( [channel] => 17 [id] => sdfdfsf3 ) )
How to remove parent array index from array
I want to remove parent array index in array. Following is my array. Array ( [0] => Array ( [0] => Array ( [id] => 296 [username] => David0123 [profile_slug] => david-love ) ) [1] => Array ( [0] => Array ( [id] => 297 [username] => Anne_wils [profile_slug] => anne-chase ) ) [2] => Array ( [0] => Array ( [id] => 300 [username] => malina001 [profile_slug] => malina-reid ) ) ) And I want like this way.. Array( [0] => Array ( [id] => 296 [username] => David0123 [profile_slug] => david-love ) [1] => Array ( [id] => 297 [username] => Anne_wils [profile_slug] => anne-chase ) [2] => Array ( [id] => 300 [username] => malina001 [profile_slug] => malina-reid ) ) I used following script for it but not work. $myMainArray = json_decode(json_encode($allEscorts),true); $i=0; foreach( array_values($myMainArray) as $k=> $val){ echo $val[$i]['id']; $i++; } I want to display data each element but first i have to remove parent array indexes.
You can use array_map to pull values up one level $myMainArray = json_decode(json_encode($allEscorts),true); $myMainArray = array_map(function($el) { return $el[0]; }, $myMainArray);
You should check if the first array could be generate as you wish. If not you can use array_map to get the first index from the inner-array. for example: $result = array_map(function($item){ return $item[0]; // always return the first array-index }, $first_array);
json array sort by value in php
I have JSON arrays of objects. I am trying to sort an array using usort. I want to use value field from field_listing_order. It sorted using value. I am missing something but not able to figure it out. please review the code. Thanks! stdClass Object ( [node_title] => abc [nid] => 2281 [field_api_order_value] => 201 [field_node_entity_type] => node [_data] => Array ( [nid] => Array ( [entity_type] => node [entity] => stdClass Object ( [title] => abc [field_listing_order] => Array ( [und] => Array ( [0] => Array ( [value] => 8 [format] => [safe_value] => 8 ) ) ) ) ) ) ) stdClass Object ( [node_title] => abc [nid] => 2243 [field_api_order_value] => 204 [field_node_entity_type] => node [_data] => Array ( [nid] => Array ( [entity_type] => node [entity] => stdClass Object ( [title] => abc [field_listing_order] => Array ( [und] => Array ( [0] => Array ( [value] => 3 [format] => [safe_value] => 3 ) ) ) ) ) ) ) stdClass Object ( [node_title] => abc [nid] => 2431 [field_api_order_value] => 242 [field_node_entity_type] => node [_data] => Array ( [nid] => Array ( [entity_type] => node [entity] => stdClass Object ( [title] => abc [field_listing_order] => Array ( [und] => Array ( [0] => Array ( [value] => 1 [format] => [safe_value] => 1 ) ) ) ) ) ) ) and So on ... foreach ($view->result as $result) { $node = $result->_data['nid']['entity']; $listing_order = $node->field_listing_order[LANGUAGE_NONE][0]; ..... // code goes here and it works well. sorting issue } usort ($node->field_listing_order[LANGUAGE_NONE][0], function($a, $b){ return strcmp($a->value, $b->value); }); ?>
If you need to sort all the nodes using the field_listing_order value, you need to compare the values along the full path, from the first object to the value: usort($view->result, function($a, $b) { $la = $a->_data['nid']['entity']->field_listing_order[LANGUAGE_NONE][0]['value']; $lb = $b->_data['nid']['entity']->field_listing_order[LANGUAGE_NONE][0]['value']; return $la - $lb ; }); In this case $a and $b are two different nodes which could be compared. That why you should compare the field_listing_order's value of these nodes. The answer is working with $la- $lb
how to get the nested array count with key values seperated in php
This is my array Array ( [2] => Array ( [0] => Array ( [id] => 2 [res_id] => 1 [grand_total] => 303.42 [time] => 2016-07-28 11:04:38 AM [status] => 0 ) [1] => Array ( [id] => 2 [res_id] => 1 [grand_total] => 303.42 [time] => 2016-07-28 11:04:38 AM [status] => 0 ) ) [1] => Array ( [0] => Array ( [id] => 1 [res_id] => 1 [grand_total] => 303.42 [time] => 2016-07-28 11:04:17 AM [status] => 0 ) ) ) From this I need sub array count i.e., the array having two indexes such as 2 & 1 from this 2 & 1 there are some nested arrays found such as 0 & 1 for each Here,I need array count as follows Array ( [2] => Array ( [count] = 2 ) [1] => Array ( [count] = 1 ) ) How should I get this.. Someone help me out of this... Thank you..
It is very easy foreach your array and use count or sizeof function. $desiredArray = array(); foreach ($myarray as $key => $value) { $desiredArray [$key] ['count'] = sizeof ($value); } print_r ($desiredArray); The output will be as your desired output Array ( [2] => Array ( [count] = 2 ) [1] => Array ( [count] = 1 ) )
It's simple, and is better to create new array where you can save count of elements of main array items: $counts = array(); foreach ($array as $k => $values) { $counts[$k] = count($values); } print($counts); // gives desired result Also you don't need to have extra array for the $counts array, what you get is: array ( 2 => 2, 1 => 1 )
php formatting array results
I have an array like the following. This is the results of a query on one of our servers. Array ( [count] => 1 [0] => Array ( [name] => Array ( [count] => 1 [0] => mac ) [0] => name [staffid] => Array ( [count] => 1 [0] => 1234 ) [1] => staffid [school] => Array ( [count] => 1 [0] => western ) [2] => school [count] => 3 [dn] => cn=mac,cn=staff ) ) How do I loop through this array and create a new array as follows. Array ( [name] => mac [staffid] => 1234 [school] => western ) I've tried a foreach loop echoing the key & values, but I'm not sure where to go from there. There will be more results returned as the query is expanded, but original array layout will be the same and the new layout needs to be the same format. Any ideas ? Thanks
Try this: $result = array(); foreach($yourArray as $element){ for($i=0;$i<$element['count']; $i++){ unset($element[$element[$i]]['count']); $result[$element[$i]] = implode(', ', $element[$element[$i]]); } }