'Populate decoded data into dropdown

I am having 2 files, one to fetch ajax and to decode it. the other (page2.php) is modal popup in which I want to populate the received data from page1.php.

page1.php is below which returns invoice numbers perfectly.

$newArr = array();
$decoded = array();
$decoded = json_decode($result, true);
foreach($decoded ['invoices'] as $result) {
    $newArr = $result['invoiceno'];
    echo $newArr; //JUST FOR DEBUGGING
}

page2.php is a modal where I try to get the received data and populate into a dropdown.

function sort_(){
    global $newArr;
    $output='';
    $output.= '<option value = '.$newArr.'>'.$newArr.'</option>';
    return $output;
}

I know I am not looping the array to sort. I have tried different ways like below which didn't work.

function sort_(){
    global $newArr;
    global $result;
    global $decoded;

    $decoded= json_decode($result, true);
    $output='';
    $output.= '<option value = "Select INO">Select Select INO</option>';
    foreach($decoded['invoices'] as $result) {
        $output.= '<option value = "'.$newArr.'">"'.$newArr.'"</option>';
    }
    return $output;
}

The error that I am getting in developer console is;

<b>Warning</b>:  Trying to access array offset on value of type null in <b>C:\xampp\htdocs\order\page2.php</b> on line <b>17</b><br />
<br />
<b>Warning</b>:  foreach() argument must be of type array|object, null given in <b>C:\xampp\htdocs\order\page2.php</b> on line <b>17</b><br />

where I am stuck?



Solution 1:[1]

  1. Get the records from the DB (In case your data is not in form of a json string in the DB you don't need to decode)

  2. Create the following functions :

function getOptions($acc, $record){
    return $acc."<option value='".$record['your key']."'>".$record['your key']."</option>" ;
}

function createOptionsHtml($records) {
    return array_reduce($records, 'getOptions') ;
}

Hope I got your problem right.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hangover Sound Sound