Skip to content
Advertisement

How do I optimise this repeating var code?

How do I make it optimised? It doesn’t really work with while for me. I need these rows of code to be in less rows.

var a[0]="<?php echo print_r($tempa[0]["descr"], true);
    ?>";
    var a[1]="<?php echo print_r($tempa[1]["descr"], true);
    ?>";
    var a[2]="<?php echo print_r($tempa[2]["descr"], true);
    ?>";
    var a[3]="<?php echo print_r($tempa[3]["descr"], true);
    ?>";
    var a[4]="<?php echo print_r($tempa[4]["descr"], true);
    ?>";
    var a[5]="<?php echo print_r($tempa[5]["descr"], true);
    ?>";
    var a[6]="<?php echo print_r($tempa[6]["descr"], true);
    ?>";
    var b[0]="<?php echo print_r($tempb[0]["descr"], true);
    ?>";
    var b[1]="<?php echo print_r($tempb[1]["descr"], true);
    ?>";
    var b[2]="<?php echo print_r($tempb[2]["descr"], true);
    ?>";
    var b[3]="<?php echo print_r($tempb[3]["descr"], true);
    ?>";
    var b[4]="<?php echo print_r($tempb[4]["descr"], true);
    ?>";
    var b[5]="<?php echo print_r($tempb[5]["descr"], true);
    ?>";
    var b[6]="<?php echo print_r($tempb[6]["descr"], true);
    ?>";

Advertisement

Answer

Say you have:

<?php 
    $tempa = [
        ["descr" => "A0"],
        ["descr" => "A1"],
        ["descr" => "A2"],
        ["descr" => "A3"],
        ["descr" => "A4"],
        ["descr" => "A5"],
        ["descr" => "A6"],
    ];

    $tempb = [
        ["descr" => "B0"],
        ["descr" => "B1"],
        ["descr" => "B2"],
        ["descr" => "B3"],
        ["descr" => "B4"],
        ["descr" => "B5"],
        ["descr" => "B6"],
    ];
?>

all you need in JavaScript is:

const a = <?= json_encode(array_column($tempa, "descr")) ?>;
const b = <?= json_encode(array_column($tempb, "descr")) ?>;
console.log(a); //  ["A0", "A1", "A2", "A3", "A4", "A5", "A6"]
console.log(b); //  ["B0", "B1", "B2", "B3", "B4", "B5", "B6"]

by using PHP’s array_column and json_encode.

Or if you like ES6 syntax:

const [a, b] = <?= json_encode([
  array_column($tempa, "descr"),
  array_column($tempb, "descr"),
]) ?>;
console.log(a, b);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement