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"}];
Nick
147k23 gold badges67 silver badges106 bronze badges
asked Feb 6, 2019 at 11:32

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]
answered Feb 6, 2019 at 11:39
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.

answered Feb 6, 2019 at 11:35

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'];
}
...
answered Feb 6, 2019 at 11:45

Comments

-1

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

answered Feb 6, 2019 at 11:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.