如何将json数据转换为php变量?

时间:2019-06-30 06:21:08

标签: php arrays json variables undefined-index

我有一个 json 文件,我想从中获取数据并将其用作循环内的 php变量

我不断收到未定义的索引错误,但这是行不通的...

这是我的代码:

$file = file_get_contents("csv/products.json",'r');   

    for($i=0;$i<18;$i++){ 

    $datosArray = json_decode($file,true);

    //var_dump($datosArray);

   if (isset ($datosArray)){
    $id =  $datosArray["id"];
    $genderid = $datosArray["sex_id"];
    $dest =  $datosArray["destaque"];
    $cat =  $datosArray["categoria"];
    $marc =  $datosArray["Marca"];
    $name =  $datosArray["nombre"];
    $desc =  $datosArray["descripcion"];
    $pho1 =  $datosArray["photo_id1"];
    $pho2 =  $datosArray["photo_id2"];
    $pho3 =  $datosArray["photo_id3"];
    $dprice = $datosArray["D_price"];
    $oprice =  $datosArray["O_price"];
    }

    ?>

这是我的json的一部分:

[
  {
    "id": 1,
    "sex_id": 101,
    "destaque": 1,
    "categoria": "Vestidos",
    "Marca": "Marfinno",
    "nombre": "Mono rayas",
    "descripcion": "Mono de rayas con botones y amarre  Marfinno",
    "photo_id1": "Female1.jpg",
    "photo_is2": "Female1.1.jpg",
    "photo_id3": "Female1.2.jpg",
    "D_price": "$100.00",
    "O_price": "$300.00"
  },
  {
    "id": 2,
    "sex_id": 101,
    "destaque": 0,
    "categoria": "Vestidos",
    "Marca": "Marfinno",
    "nombre": "Mono liso",
    "descripcion": "Mono liso con amarre  Marfinno",
    "photo_id1": "Female2.jpg",
    "photo_is2": "Female2.1.jpg",
    "photo_id3": "Female2.2.jpg",
    "D_price": "$100.00",
    "O_price": "$300.00"
  }, 

谢谢。

1 个答案:

答案 0 :(得分:1)

这里有一个错误:

$file = file_get_contents("csv/products.json",'r'); 

简单地说:

$file = file_get_contents("csv/products.json"); 

file_get_contents不需要像打开文件时那样的'r'参数。参见https://www.php.net/manual/en/function.file-get-contents.php


然后,在有关var_dump的注释中,您必须看到有一个数组数组。

array(54) { 
    [0]=> array(12) { 
        ["id"]=> int(1) 
        ["sex_id"]=> int(101) 
        ["destaque"]=> int(1) 
        ["categoria"]=> string(8) "Vestidos" 
        ["Marca"]=> string(8) "Marfinno" 
        ["nombre"]=> string(10) "Mono rayas" 
        ["descripcion"]=> string(44) "Mono de rayas con botones y amarre Marfinno" 
        ["photo_id1"]=> string(11) "Female1.jpg" 
        ["photo_is2"]=> string(13) "Female1.1.jpg" 
        ["photo_id3"]=> string(13) "Female1.2.jpg" 
        ["D_price"]=> string(7) "$100.00" 
        ["O_price"]=> string(7) "$300.00" 
    } 
    [1]=> array(12) {
        ....
    }

因此,当您要引用一个项目时,必须放置2个索引:

...
$id =  $datosArray[$i]["id"];
$genderid = $datosArray[$i]["sex_id"];
...

如果将那部分代码保留在for循环的上下文中,这将起作用。