PHP fill up an associative array - php

I'm creating a data.php file which returns a json file to a html file where I fill up a grid with the data from the data.php file.
I need this to be an associative array in the following form:
[
{"CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative"},
{"CompanyName":"Ana Trujillo Emparedados y helados","ContactName":"Ana Trujillo","ContactTitle":"Owner"},
{"CompanyName":"Antonio Moreno Taquera","ContactName":"Antonio Moreno","ContactTitle":"Owner"}
]
Now the problem is, I want this data.php to be sort of generic, which means I don't know the columnnames nor the the amount of columns.
The only way I get this done, is by using a switch statement but this is not ideal (because I can make a number of cases but what if the table has one more column) nor is it very elegant.
I bet this can be done far better, any ideas ?
I tried using array_push() but that doesn't work with associative arrays.
// get columnnames
for ($i = 0; $i < $result->columnCount(); $i++) {
$col = $result->getColumnMeta($i);
$columns[] = $col['name'];
}
// fill up array
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
switch (count($columns);) {
case 1 :
$records[] = array($columns[0] => $row[$columns[0]]);
break;
case 2 :
$records[] = array($columns[0] => $row[$columns[0]], $columns[1] => $row[$columns[1]]);
break;
case 3 :
$records[] = array($columns[0] => $row[$columns[0]], $columns[1] => $row[$columns[1]], $columns[2] => $row[$columns[2]]);
break;
case ... // and so on
}
}
// send data to client
echo json_encode($records);

change the switch code segment with this one
$arr_tmp = array();
for($i = 0; $i < count($columns); $i++)
{
$arr_tmp[$columns[$i]] = $row[$columns[$i]];
}
$records []= $arr_tmp;

You could iterate over the columns:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$values = array();
foreach ($columns as $column) {
values[$column] = $row[$column];
}
records[] = $values;
}

Related

Expand (json) object in php

I want this sql-query result (from a log file, i hope it's accurate)
[
{"id":"1","text":"123"}
,{"id":"2","text":"456"}
] []
to become this
{
1: {"id":"1","text":"123"}
,2: {"id":"2","text":"456"}
}
I tried array_push and array_combine but am new to PHP and was unsuccessful so far.
Short: I want to add keys (starting with 1) to an array of objects.
One attempt
$i = 1;
while ($row = fetchRow($result)) {
array_push($arr_result, $row);
array_push($i, $arr_result);
$i++;
}
But $arr_result looks like the first code sample.
You dont need $i using $arr_result[] will create a new occurance in your array.
while ($row = fetchRow($result)) {
// this forces the array to start at 1 instead of 0 if thats what you really want
if (count($arr_result) == 0){
$arr_result[1] = $row;
} else {
$arr_result[] = $row;
}
}
Or if the key is supposed to be the id from the row
while ($row = fetchRow($result)) {
$arr_result[$row['id']] = $row;
}

PHP combine matching rows from associative arrays from sql and display results in html

I have 2 results set
$result_a = #pg_query($rquery_a);
$result_b = #pg_query($rquery_b);
I have 2 arrays to host and display the data on an html page:
$datas_a = array();
$datas_b = array();
$datas_a gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_occu' => $row['duree_resa']);
$i++;
}
and $datas_b gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
From these 2 existing arrays with same number of rows and same keys, I would like 3 columns, 1 column is the same for both arrays ($datas_a and $datas_b), the second column is from $datas_a and the third column is from $datas_b
It currently looks like this for $datas_a
$datas_a
It currently looks like this for $datas_b
$datas_b
It should look like this
merging columns
Now, I have used
$dataComb = array_merge($datas_a, $datas_b);
but it puts one array on top of the other while I would like to just add a column
try
$i=0;
foreach ($datas_a as $data) {
$dataComb[$i]["s1"] = $data["s1"];
$dataComb[$i]["duree_resa"] = $data["duree_resa"];
$i++;
}
$i=0;
foreach ($datas_b as $data) {
$dataComb[$i]["duree_cours"] = $data["duree_cours"];
$i++;
}
Edit - 2021-08-20
Or for something more robust given it's a basic way I only know to do this
$datas_a = array(); // associative array
$datas_b = array();
$dataComb = []; // indexed array
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_resa' => $row['duree_resa']);
$i++;
}
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
$i=0;
if($a>=$b){
foreach($datas_a as $dataa) {
$dataTmp[$i][0] = $dataa["s1"];
$dataTmp[$i][1] = $dataa["duree_resa"];
foreach($datas_b as $datab) {
if($dataa["s1"] == $datab["s1"] ){
$dataTmp[$i][2] = $datab["duree_cours"];
}
}
$i++;
}
}
elseif($a<$b){
foreach($datas_b as $datab) {
$dataTmp[$i][0] = $datab["s1"];
$dataTmp[$i][1] = $datab["duree_resa"];
foreach($datas_a as $dataa) {
if($datab["s1"] == $dataa["s1"] ){
$dataTmp[$i][2] = $dataa["duree_cours"];
}
}
$i++;
}
}
$nb_lig = $a>=$b ? $a : $b;
for ($row=0; $row<=$nb_lig; $row++) {
$dataComb[$row]["s1"] = $dataTmp[$row][0];
$dataComb[$row]["duree_resa"] = $dataTmp[$row][1];
$dataComb[$row]["duree_cours"] = $dataTmp[$row][2];
}
And there is $dataComb as an associative array that combines the data from previous arrays with matching records
foreach ($dataComb as $data){
echo '<tr>';
echo '<td>'.$data["s1"].'</td>';
echo '<td>'.$data["duree_resa"].'</td>';
echo '<td>'.$data["duree_cours"].'</td>';
echo '</tr>';
}

How to merge values from similar rows in an array to rows containing both data in php

I have a phone book array I get from a database, where everyone appears once with their stationary phone number and a second with their mobile number.
I need to make this an array where everyone has only one line, with their phone number and mobile number
//My array
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
//The result that should come out
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244','phone'=>''),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778','phone'=>'04472861558878')
);
I would do it the following way:
first I would generate a unique key that identify the row (in your case the name and the family, for example).
then check if a element with the same key exist, if it already exist merge the two component.
Optional if you only want an array of values transform the result with array_value function.
$dataArray = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
$result = [];
foreach($dataArray as $data){
//Just in case that the name or the family is not assigned (operator ??)
$key = ($data['name']??'').'-'.($data['family']??'');
$result[$key] = array_merge($result[$key]??[],$data);
}
//Optional, get only the array values
$result = array_values($result);
I did so
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
count($data) < 2 ? exit(): $data;
for($i=0;$i<count($data);$i++){
$array_unique[$i] = $data[$i]["name"];
$array_unique[$i] = $data[$i]["family"];
}
$array_unique = array_unique($array_unique);
if(count($array_unique) == 1){
$last_array[0]=$array_unique[0];
$last_array[0]["phone"]=$array_unique[0]["phone"];
}
else{
$array_uniqueKeys = array_keys($array_unique);
for($i = 0;$i < count($array_unique);$i++){
$firstIndex = $i + 1;
$firstIndex == count($array_unique) ? $nextKey = count($data) : $nextKey = $array_uniqueKeys[$firstIndex];
$paar = $nextKey - $array_uniqueKeys[$i];
$dataslice = array();
$i3=0;
for($i2 = $array_uniqueKeys[$i];$i2 < ($array_uniqueKeys[$i]+$paar);$i2++){
if(in_array($i2,$array_uniqueKeys)){
$last_array[$i]=$data[$i2];
}
else{
$last_array[$i]["phone"]=$data[$i2]["phone"];
}
$i3++;
}
}
}
print_r($last_array);

GFAPI submit_form() function in loop

I'm struggling with GFAPI's function submit_form() when it's used in loops. For unknown reason it often merges data from other loops into one, the outcome of this situation is that only the very first entry is added in a proper way, the rest seems to be empty.
I can't use other function although I've tried - and it worked (add_entry() for example). I need to use QR generation and attach them to the notification, and these codes are generated when the form is submitted.
CSV file has at least 3 columns: email, full_name and phone_number. Here's my code:
function generateData($filename, $date, $id){
$rows = array_map('str_getcsv', file($filename));
$header = array_shift($rows);
$csv = array();
foreach($rows as $row) {
$csv[] = array_combine($header, $row);
}
$count_array = count($csv);
for ($i=0; $i < $count_array; $i++) {
foreach ($csv[$i] as $key => $value) {
// delete rows that we don't need
if ($key != 'email' && $key != 'full_name' && $key != 'phone_number') {
unset($csv[$i][$key]);
}
}
}
insertGFAPI($csv);
}
function insertGFAPI($entries){
$count_entries = count($entries);
for ($i=0; $i < $count_entries; $i++) {
$data[$i]['input_1'] = $entries[$i]['email'];
$data[$i]['input_2'] = $entries[$i]['full_name'];
$data[$i]['input_3'] = $entries[$i]['phone_number'];
$result = GFAPI::submit_form( get_option('form-id'), $data[$i]);
}
The outcome that I'd like to get is pretty simple - I want to know why and how is it possible that submit_form() merges data from other loops and how I can prevent it.
Do you know what can I do with that?
Solved. It was necessary to empty $_POST array.

php compare two associative array value

MySQL array
CSV file array
I want to match this two different associative arrays "Url" value. Also I want remaining array value of CSV file i.e. DA, PA, MozRank, Linksln, and so on...
I hope some genius can help me
Thank you
Check this custom PHP script returns you matched url from two array
<?php
/**
* Function for match url and return data
*/
function matchArray($array1, $array2)
{
$index = 0;
$return = array();
$count1 = count($array1);
$count2 = count($array2);
for($i=0; $i < $count1; $i++)
{
for($j=0; $j < $count2; $j++)
{
if($array1[$i]['url'] == $array2[$j]['url']) {
$return[$index]['url'] = $array2[$j]['url']; // Add index which you want to get
$return[$index]['DA'] = $array2[$j]['DA']; // Add index which you want to get
$return[$index]['PA'] = $array2[$j]['PA'];
$return[$index]['MozRank'] = $array2[$j]['MozRank'];
}
$index ++;
}
}
echo "<pre>";
print_r($return); // this will return matched url form two array
}
$array1 = array(array('url' => 'AllConsuming.net' ),array('url' => 'app.brand-mention.com'),array('url' => 'www.microsoft.com'));
$array2 = array(array('url' => 'AllConsuming.net', 'DA' => 48, 'PA'=> 54.4, 'MozRank'=> 5.4),array('url' => 'www.microsoft.com', 'DA' => 31.7, 'PA'=> 54.4, 'MozRank'=> 5.4));
matchArray($array1, $array2); // calling function
?>
If you want to know which entries are indentical, proceed this way :
$array1 = array_column($ar1, 'url'); // return array('AllConsuming.net', 'http://app.brand-mention.com', 'https://www.microsoft.com', 'otherstuff')
$array2 = array_column($ar2, 'url'); // return array('AllConsuming.net', 'TravelIntelligence.net', 'otherstuff')
// compare these 2 arrays
$comp = array_intersect($aray1, $array2);
var_dump($comp); // output array('AllConsuming.net', 'otherstuff');

Categories