0

I will need to read this file with PHP. I need to get the name of the city to add it inside a wordpress custom db table. At the moment I'm doing this

$cities = json_decode(require_once plugin_dir_path(__FILE__) . '/inc/cities.json');

foreach( $cities as $key => $val ){
 var_dump($key, $val);
 $wpdb->insert(
  $tablename,
  'city_name' => $val
 );
}


But I'm not able to get the nome field from the resulting array of the parsed json file. What is the correct way to parse the file and loop it to extract the needed data and pass it to the insert function of WordPress?

newbiedev
  • 2,607
  • 3
  • 17
  • 65
  • 1
    If you notice in your dump, `$key` is just an array key, `$val` is an object with properties. So it should be `$val->nome` – aynber Oct 18 '22 at 17:42
  • ok. If I want to take the value of a particular key? – newbiedev Oct 18 '22 at 17:53
  • Then I guess you need to know the key. Or loop through until you find the value you're looking for. – aynber Oct 18 '22 at 17:54
  • the key is the same for all the values into the json file in this case `regione`. I can do `$key['regione']->name` ? – newbiedev Oct 18 '22 at 17:56
  • No, `$key` is a number. There are no actual array keys for the parent array in your json, so it becomes a numbered array. – aynber Oct 18 '22 at 18:06
  • ok, I've done a test and seems working as you have suggested. If you post a reply I will accept it. Thank you for the help :) – newbiedev Oct 18 '22 at 18:10
  • @aynber in wordpress this will not work like in php standard – newbiedev Oct 19 '22 at 21:28
  • Wordpress uses standard PHP, it just has it's own extra functions. So anything that works in standard PHP works in Wordpress. – aynber Oct 20 '22 at 11:58
  • I've tried by doing a test in a single php file and the loop worked fine. In wordpress inside a method of my plugin instead I'm unable to loop it and insert data, it's very strange. do I need to require the file or read it using `file_get_contents()` – newbiedev Oct 20 '22 at 16:53

0 Answers0