I have a multidimensional array of data that is presented as follows:
Array
(
[0] => Array
(
[CallID] => 793415338
[StartTime] => 2016-10-04 17:21:53
[CallingNo] => +15555555555
[queue1_time] => 94
)
[1] => Array
(
[CallID] => 1718936847
[StartTime] => 2016-10-04 17:29:41
[CallingNo] => +15555555556
[queue1_time] => 64
[queue2_time] => 96
)
[2] => Array
(
[CallID] => 497342634
[StartTime] => 2016-10-04 17:34:57
[CallingNo] => +15555555557
[queue4_time] => 47
)
[3] => Array
(
[CallID] => 1298245252
[StartTime] => 2016-10-04 17:35:33
[CallingNo] => +15555555558
[queue1_time] => 5
)
[4] => Array
(
[CallID] => 1214106933
[StartTime] => 2016-10-04 17:35:38
[CallingNo] => +15555555559
[queue1_time] => 53
[queue2_time] => 31
)
....
)
I would like to parse all of the data in this array and convert it to a csv with a header above each set of array values that have matching complete key sets. Output would look like the following:
CallID,StartTime,CallingNo,queue1_time
793415338,2016-10-04 17:21:53,+15555555555,94
1298245252,2016-10-04 17:35:33,+15555555558,5
CallID,StartTime,CallingNo,queue1_time,queue2_time
1718936847,2016-10-04 17:29:41,+15555555556,64,96
1214106933,2016-10-04 17:35:38,+15555555559,53,31
CallID,StartTime,CallingNo,queue4_time
497342634,2016-10-04 17:34:57,+15555555557,47
Any further tips or tricks to shorten this code would be greatly appreciated!
I was able to get this functional with the following code but I am guessing there is a simpler more efficient method to perform this task:
$key_array = array();
foreach (array_keys($overflow_array) as $paramName){
foreach ($overflow_array[$paramName] as $key => $value){
$key_array[$paramName][] = $key;
}
}
$key_array = array_map("unserialize", array_unique(array_map("serialize", $key_array)));
function array_keys_exist($keys, $array){
if (count($keys) != count($array)){
return false;
}
foreach($keys as $num => $key){
if(!array_key_exists($key, $array))return false;
}
return true;
}
$output = fopen('php://temp/maxmemory:1048576', 'w');
if($output === FALSE) {
die('Failed to open temporary file');
}
foreach ($key_array as $keyset => $value){
$keys = array_values($value);
fputcsv($output, $keys);
foreach ($overflow_array as $oflow => $oflow_key){
if (array_keys_exist($keys, $overflow_array[$oflow]) == true){
fputcsv($output, $overflow_array[$oflow]);
}
}
}
rewind($output);
$csv = stream_get_contents($output);
fclose($output);
print_r($csv);
Related
I am parsing A JSON file in PHP using PHP Decode
$json= file_get_contents ("resultate.json");
$json = json_decode($json, true);
and then I am trying to loop through the results and display them
foreach($json as $zh){
$name = $zh[0]["VORLAGEN"][0]["JA_PROZENT"];
$JA = $zh[0]["VORLAGEN"][0]["VORLAGE_NAME"];
$kreis = $zh[0]["NAME"];
$kreis1 = $zh[22]["NAME"];
echo $name;
echo $JA;
echo $kreis;
echo $kreis1;
...}
but I receive only one element e.g. position 0 or position 22. I would like to receive all the results and display them in a list. Below you can see the array
Array
(
[GEBIETE] => Array
(
[0] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 205
[STIMMBETEILIGUNG] => 28.11
[NEIN_STIMMEN_ABSOLUT] => 183
[VORLAGE_ID] => 2491
[JA_PROZENT] => 52.84
)
)
[NAME] => Aeugst a.A.
[WAHLKREIS] => 0
[BFS] => 1
)
[1] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 1000
[STIMMBETEILIGUNG] => 26.15
[NEIN_STIMMEN_ABSOLUT] => 851
[VORLAGE_ID] => 2491
[JA_PROZENT] => 54.02
)
)
[NAME] => Affoltern a.A.
[WAHLKREIS] => 0
[BFS] => 2
)
[2] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 661
[STIMMBETEILIGUNG] => 30.98
[NEIN_STIMMEN_ABSOLUT] => 454
[VORLAGE_ID] => 2491
[JA_PROZENT] => 59.28
)
)
[NAME] => Bonstetten
[WAHLKREIS] => 0
[BFS] => 3
)
can you please tell me how to print all the elements of this array?
There is GEBIETE layer in your json, so change foreach($json as $zh) to foreach($json["GEBIETE"] as $zh) will works.
You can nest multiple foreach:
$root = $json['GEBIETE'];
foreach ($root as $elem) {
foreach ($elem as $key => $value) {
// VORLAGEN is an array of its own so if you want to print the keys you should foreach this value as well
if(is_array($value)) {
foreach ($value[0] as $k => $v) {
echo $k."\t".$v;
}
}
else {
echo $value;
}
}
}
I have struggle in set start point in PHP array
PHP CODE
for($k=0; $k<count($AddClmn); $k++){
$ord = 0;
foreach($AddClmn[$k] as $ky=>$vl){
$clmns[] = array('head'=>$ky, 'src'=>$vl, 'typ'=>'datatyp', 'NEMERIC'=>'', 'wdth'=>'70', 'ord'=>$ord);
$ord++;
}
}
file_put_contents('Tracing.txt', print_r($clmns, true));
My actual output is above PHP code
Array
(
[0] => Array
(
[head] => locid
[src] => 1
[typ] => datatyp
[NEMERIC] =>
[wdth] => 70
[ord] => 0
)
[1] => Array
(
[head] => hhs
[src] => 2525252
[typ] => datatyp
[NEMERIC] =>
[wdth] => 70
[ord] => 1
)
[2] => Array
(
[head] => LA0
[src] => 9831808.388559164
[typ] => datatyp
[NEMERIC] =>
[wdth] => 70
[ord] => 2
)
)
in above result i want skip first two array and i want 3 rd array as start with index 0. how to set pointer or any way to face this situation? i except result is
[0] => Array
(
[head] => LA0
[src] => 9831808.388559164
[typ] => datatyp
[NEMERIC] =>
[wdth] => 70
[ord] => 2
)
[1] => Array
(
[head] => LA1
[src] => 12920638.804462105
[typ] => datatyp
[NEMERIC] =>
[wdth] => 70
[ord] => 3
)
how to solve this prob ?
I think you need this -
foreach($AddClmn[$k] as $ky=>$vl){
if(substr( $ky, 0, 2 ) === "LA") {
//your code
}
} // end for loop
for($k=2; $k<count($AddClmn); $k++){
$ord = 0;
foreach($AddClmn[$k] as $ky=>$vl){
$clmns[] = array('head'=>$ky, 'src'=>$vl, 'typ'=>'datatyp', 'NEMERIC'=>'', 'wdth'=>'70', 'ord'=>$ord);
$ord++;
}
}
file_put_contents('Tracing.txt', print_r($clmns, true));
Use this code..
//you have an array like that
$data = array(
'0' => 'Hello', //you want to skip this
'1' => 'Hello1', //you want to skip this
'2' => 'Hello2',
);
$skipped = array('0', '1');
foreach($data as $key => $value){
if(in_array($key, $skipped)){
continue;
}
//do your stuf
}
// The following lines will remove values from the first two indexes.
unset($array[0]);
unset($array[1]);
// This line will re-set the indexes (new array will set from '0' index)
$array = array_values($array);
// The following line will show the new content of the array
print_r($array);
With PHP >= 5.3 Use this function to flatten (aka remove one "layer") your array by one level:
function flatten(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
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));
I am working in multidimensional array, i have an array like this and i want to merge array
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19
[productId] => 50
)
[1] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 20
[productId] => 50
)
All i need is to make array by join orderId 19,20
ie,
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 50
)
I want to arrange like this.please help me to achieve this
You can try something like this
//This is your old array that you describe in your first code sample
$old_array = array();
// This will be the new joined array
$new = array();
// This will hold the key-pairs for each array within your initial array
$temp = array();
// This will hold all the values of orderId
$orderId = array();
// Loop through each first-level array with the original array
foreach($old_array as $val) {
//Loop through each second-level array
foreach($val as $key => $value) {
// Set the key-pair values in the $temp array
$temp[$key] = $temp[$value];
if($key == "orderId") {
// Add the current orderId value to the orderId array
array_push($orderId,$value);
// Join all the orderId values into the $temp array
$temp[$key] = join(",", $orderId);
}
}
}
//Push the final values to the new array to get a 2 dimensional array
array_push($new, $temp);
Note: I did not test any of the following code so it is very likely to not work at first.
This is also VERY bad array design and there are more likely easier and more practical solutions to this problem, but you will need to give more details on what you want to achieve
$original_array = array(); //this is the array you presented
$new_array = array(); //this is the output array
foreach($original_array as $arr) {
foreach($arr as $key => $value) {
if(array_key_exists($key, $new_array)) { //if you already assigned this key, just concat
$new_array[0][$key] .= "," . $value;
} else { //otherwise assign it to the new array
$new_array[0][$key] = $value;
}
}
}
It will give you the desired result
$arrNew = array();
$i = 0;
foreach($multiDArray as $array)
{
foreach($array as $key=>$value)
{
if($i > 0)
{
if($arrNew[$key] != $value)
{
$str = $arrNew[$key].','.$value;
$arrNew[$key] = $str;
}
}
else
{
$arrNew[$key] = $value;
}
}
$i++;
}
print_r($arrNew);
Result:
Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 1
)
I have this array:
Array (
[061716v] => 1
[061610A] => 1
[062433AP] => 1
[063868M] => 2
[059173V] => 3
[061579A] => 3
[062404AP] => 3
[059179V] => 4
[061582A] => 4
[061697V] => 4
[062407AP] => 4
)
How can i get this:
Array (
[1] => 061716v,061610A,062433AP
[2] => 063868M
[3] => 059173V,061579A,062404AP
[4] => 059179V,061582A,061697V,062407AP
)
In PHP single foreach() will do the job:-
$final_array = [];
foreach($initial_array as $key=>$val){
$final_array[$val] = isset($final_array[$val]) ? $final_array[$val].','.$key : $key;
}
print_r($final_array);
Output:-https://3v4l.org/lSKE2
// You also can use implode to skip isset checks
$group = [];
foreach ($initialArray as $key => $value) {
$group[$value][] = $key;
}
$result = array_map(function($v) { return implode(",",$v); }, $group);
print_r($result);