从json数据中获取数据表结构

时间:2016-02-26 04:43:20

标签: php mysql arrays json

我有一个像

这样的数据库(mysql)表
id |  party  |  rights    | m_id
---+---------+------------+---------
9  |abc      | 3,5,6      | ["12,","15,"6"]
20 |xyz      |  5,2       | ["6,","2,"9","12"]
21 |xyz 1    |  5,2       | ["6,","9,"12"]

现在我想以这种方式制作我的桌子 权利5的搜索结果是[" 12,"," 15," 6"] [" 6,"," 2 ," 12"] [" 6,"," 9," 12"]

12 | abc,xyz,xyz1 |

15 | ABC |

6 | abc,xyz,xyz1 |

9 | xyz,xyz1 |

2 个答案:

答案 0 :(得分:2)

让我们从我相信你已经拥有的东西开始吧。这是sscce。如果你调整mysql凭据,它应该在你的系统上运行,只创建一个临时的MySQL表。它使用PDO来访问MySQL服务器。你实际使用哪个API 并不重要(即只要其他API是mysqli,因为mysql_ *函数are depreacted; - ))

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
setup($pdo);

$statement = $pdo->prepare('
    SELECT
        *
    FROM
        soFoo
    WHERE
        FIND_IN_SET(:right, rights)
');

$statement->execute( array(':right'=>5) );

/* in one way or another you have a loop where you fetch the records
having '5' in the `rights` field
*/
foreach( $statement as $row ) {
    echo $row['party'], ' ', $row['show_ids'], "\r\n";
}


function setup($pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE soFoo
    (`id` int, `party` varchar(9), `exc` varchar(13), `rights` varchar(5), `show_ids` varchar(27))
   ');
  $pdo->exec( <<< eos
        INSERT INTO soFoo
            (`id`, `party`, `exc`, `rights`, `show_ids`)
        VALUES
            (9, 'Percept', 'Non-Exclusive', '3,5,6', '["12,","15,"6"]'),
            (20, 'Tata Sky', 'Non-Exclusive', '5,4,', '["6,","9,"11"]'),
            (21, 'Tata Sky', 'Exclusive', '5,4', '["6,","13","15,"2","4","9"]'),
            (22, 'Simbiotic', 'Exclusive', '6,2', '["12,","15,"1","6","7","8"]')
eos
    );
}

打印

Percept ["12,","15,"6"]
Tata Sky ["6,","9,"11"]
Tata Sky ["6,","13","15,"2","4","9"]

并且(据我所知这个问题)就你已经得到的而言。

现在让我们decode the JSON array并检查whether it contains元素9。如果它确实将当前行的信息添加到名为$parties

的数组中
$parties = array();
/* in one way or another you have a loop where you fetch the records
having '5' in the `rights` field
*/
foreach( $statement as $row ) {
    $ids = json_decode($row['show_ids'], true);
    if ( in_array('9', $ids) ) {
        $parties[$row['id']] = $row['party'];
    }
}
var_export($parties);

打印

array (
  20 => 'Tata Sky',
  21 => 'Tata Sky',
)

但是......从关系数据库的角度来看,这是......次优的 FIND_IN_SET子句阻碍了MySQL有效地使用索引;您在单个字段中搜索(复合)数据。令人惊讶的是,数据库服务器实现可以做些什么来提高性能;但它有限制。
并且您还将可能不必要的数据从MySQL服务器传输到php实例(5rights9show_ids GuestRow = React.createClass({ getInitialState() { return { attending: this.props.data.attending, plusOneAttending: this.props.data.plusOneAttending } }, handleCheckboxChange(field, event) { if(field == 'plusOne') { this.setState({ plusOneAttending: event.target.checked }); } else if (field == 'guest') { this.setState({ attending: event.target.checked }); } else { console.log("error third option for field"); } }, plusOneRow() { return ( this.props.data.hasPlusOne ? <input type="checkbox" name="plusOneAttending" defaultChecked={this.state.plusOneAttending} onChange={this.handleCheckboxChange.bind(this, 'plusOne')} /> : <span>Sorry you don't have a plus one</span> ) }, render(){ return( <tr> <td> <span>{this.props.data.name}</span> </td> <td> <input type="checkbox" name="attending" defaultChecked={this.state.attending} onChange={this.handleCheckboxChange.bind(this, 'guest')} /> </td> <td> {this.plusOneRow()} </td> </tr> ); } }); 中的RsvpForm = React.createClass({ getInitialState() { return { guests: this.props.data.guests } }, saveChanges(event) { event.preventDefault(); //console.log(test); }, render() { var guestRows = this.state.guests.map(function(guest){ return ( <GuestRow callBackToParent={this.onChildChange} data={guest} /> ) }, this); return ( <div id="rsvp"> <span>Welcome {this.props.data.invitationName}! Thank you for taking part in our wedding!</span> <br /> <table> <thead> <tr> <th>Guest</th> <th>Are you attending?</th> <th>Plus one?</th> </tr> </thead> {guestRows} </table> <br /> <button onClick={this.saveChanges}>Save!</button> </div> ) } }); 。如果可能,应该避免这种情况。网络/网络堆栈速度快且可以优化,RAM很便宜......但同样存在限制。

所以,我建议你一方面调查Database normalization,另一方面调查document-oriented databases

答案 1 :(得分:0)

我将在下面给出一个例子,以便你可以按照自己的方式写作,

如果您有下表

id | name    
1  | a,b,c    
2  | b

和预期的输出

id | name    
1  | a    
1  | b    
1  | c    
2  | b

然后按照以下解决方案

如果您可以创建一个数字表,其中包含从1到要拆分的最大字段的数字,您可以使用这样的解决方案:

select
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  numbers inner join tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

请参阅小提琴here.

如果您无法创建表格,那么解决方案可以是:

select
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

示例小提琴是here.