0

I want to pass an array from PHP to Javascirpt so I just get a list of values - currently I get JSON format - which I know because I'm using JSON_ENCODE I'm just hoping/wondering is there a way to pass it as a simple set of values or to parse it afterwards?

Apologies I'm quite new to this :)

I've tried a few different things from previous answers to similar questions, but none seem to do the trick.

<?php 

$user = 'xxx';
$pass = 'xxx';
$connection_string = 'connectionstringtomysqldatabase';

$connection = odbc_connect( $connection_string, $user, $pass ); 
$sqlstring = "SELECT FIELD1 FROM TABLE.ITEM where IASOHQ<>0 FETCH FIRST 10 ROWS ONLY";
$result = odbc_exec($connection, $sqlstring);

while ($info = odbc_fetch_array($result)) {
$content[] = $info;
}

?>

<script type="text/javascript">

var content = <?php echo json_encode($content); ?>;

</script>

I want...

var content = [68,116,49,57,13,11,46,47,14,79]

I get...

var content = [{"FIELD1":"68"},{"FIELD1":"116"},{"FIELD1":"49"},{"FIELD1":"57"},{"FIELD1":"13"},{"FIELD1":"11"},{"FIELD1":"46"},{"FIELD1":"47"},{"FIELD1":"14"},{"FIELD1":"79"}];

4 Answers 4

2

You are getting this result because your array is multi-dimensional with associative second level keys i.e. it looks like

$content = [['FIELD1' => 68], ['FIELD1' => 116], ..., ['FIELD1' => 79]];

This is because odbc_fetch_array returns an associative array for each row. To fix your data format, just change this line:

$content[] = $info;

to

$content[] = $info['FIELD1'];

That will give you an array that looks like your desired result of

[68,116,49,57,13,11,46,47,14,79]
Sign up to request clarification or add additional context in comments.

Comments

0

Just add ' to make it a value. Change

var content = <?php echo json_encode($content); ?>;

to

var content = '<?php echo json_encode($content); ?>';
var myObject = JSON.parse(content);

Iterate over the array then.

Comments

0

Just change this peace of php code. I think that all of the index of array is FIELD1

...
while ($info = odbc_fetch_array($result)) {
$content[] = $info['FIELD1'];
}
...

Comments

-1

Just
echo json_encode(array_values($content)); it will work;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.