将JS变量等同于json编码的php数组值,而不管索引如何

时间:2019-07-08 14:42:49

标签: javascript php

我正在将JS变量与json编码的php数组值进行比较,该值目前按原样工作:

function myFunction() {
    var itemArray = <?php echo json_encode($items);?>;   
    console.log(itemArray);

    var number = 14;

    if(number == itemArray[0]['number']){
        success.style.display = "block";
        error.style.display = "none";
    }
}

[{
    0:
        name: "nameOne"
        number: 14
    1:
        name: "nameTwo"
        number: 13
    2:
        name: "nameThree"
        number: 8
}]

$items: array:3 [
    0=>array{
        name: "nameOne"
        number: 14
    }
    1=>array{
        name: "nameTwo"
        number: 13

    }
    2=>array{
        name: "nameThree"
        number: 8
    }
]

因此它被索引为零,这对于测试比较来说是很好的,但这不是我想要的。我希望能够查看此对象中每个索引的“数字”字段。所以基本上我想说“如果在这里的任何索引中14作为'Number'存在,那么这应该是正确的。”

我最终也想对其他字段执行此操作,但是当我将索引更改为if(number == itemArray[]['number']){时,它表示该函数未定义。

我该如何使对象中的任何索引查看该字段?

2 个答案:

答案 0 :(得分:1)

如果您只想排列与键匹配的对象数组,请尝试此操作。第二个函数返回匹配索引的数组,尽管可能有更好的方法。

var array = [{
        name: "nameOne",
        number: 14
    },{
        name: "nameTwo",
        number: 13

    },{
        name: "nameThree",
        number: 8
    },{
        name: "nameThree",
        number: 14
    }
];
   
function findMatches(array, key, value) {
    return array.filter(item => item[key] == value);
}

function findIndex(array, key, value) {
    return array.map((item,index) => item[key] === value ? index :    undefined).filter(x => x !== undefined);
}
console.log(findMatches(array, "number", 14));
console.log(findIndex(array, "number", 14));
console.log(findMatches(array, "number", 13));
console.log(findIndex(array, "number", 13));
console.log(findMatches(array, "number", 2));
console.log(findIndex(array, "number", 2));

答案 1 :(得分:1)

<?php
//I suppose Your items will be like
$items = 
array(array("name" => "nameOne","number" => 14),
    array("name"=> "nameTwo","number"=> 13),
     array("name"=> "nameThree","number"=> 8)
);

echo "<pre>";
print_r($items);
?>

<script>
myFunction();
function myFunction() {
  //Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
   var json  = JSON.parse('<?php echo json_encode($items);?>');   
   console.log(json );

   var number = 14;
   var result = false;
   var error = '';
   //Use the loop to get the value from json
  for(var i = 0; i < json.length; i++) {
    var obj = json[i];

   //If obj.number is 14 add your code
   if(number == obj.number){
      result = true;

   }
  }

 if(result){
    alert('success message');
    success.style.display = "block";
    error.style.display = "none";
 }else{
    success.style.display = "none";
    error.style.display = "block";
 }

}
</script>