Help us understand the problem. What is going on with this article?

Googleのスプレッドシートでphpの連想配列を作る自作関数

More than 1 year has passed since last update.

phpのテスト用データ作るときによく使うので備忘録として

1行目をキー、2行目以降を値とした以下のようなテーブルがあったとする

A B C
1 id label value
2 1 'abc' 'ABC'
3 2 'def' 'DEF'

下記スクリプトを用意し、=PHP_ARRAY(A1:C1, A2:C2)のように記述するとarray('id' => 1, 'label' => 'abc', 'value' => 'ABC'),のような連想配列ができる
※ヘッダは""を省略した文字列として扱い、その他はそのままとする

script
/**
 * phpの連想配列作成
 * @param {array} header ヘッダ文字列
 * @param {array} values 値
 */
function PHP_ARRAY(header, list) {
  var result = 'array(';

  if(header[0].length == list[0].length) {
    for (var index = 0; index < header[0].length; index++) {
      if(list[0][index] != '') {
        result += "'" + header[0][index] + "' => " + list[0][index] + ",";
      }
    }
    result += ')';
  } else {
    throw new Error('header, list length not match');
  }

  return result;
}

範囲を引数に渡した場合、関数側では以下のような情報を受け取る
つまり2行目の1列目のセル内容が欲しい場合はargs[1][0]のようにすれば取得できる

array
[
    [1行目1列目 セル内容],
    [1行目2列目 セル内容]
],
[
    [2行目1列目 セル内容],
    [2行目2列目 セル内容]
],
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away