2016-11-28 129 views
0

假設我想將類似twitter的帖子中的hashtag存儲在它自己的hashtags表中。我遇到的問題是,它看起來好像這個循環將字符串「Array」存儲在hashtag名稱列中,而不是實際匹配。這似乎是一個問題,因爲返回的數組是多維的?你可以看到,我試圖通過在第0點調用數組來解決這個問題,但是這並不奏效。Preg_match_all返回多維數組 - 訪問元素時遇到問題

也許問題是在調用的函數:

function attach_hashtag($dbh, $pid, $tagname) { 
//insert into Tagged 

try { 
$sql = 'INSERT INTO Tagged (hashtag_name, post_id) 
     VALUES (:name, :pid);'; 
$stmt = $dbh->prepare($sql); 
$stmt->bindParam(':name', $tagname); 
$stmt->bindParam(':pid', $pid); 
$stmt->execute(); 

$array = [ 
    'status' => 1, 
    ]; 
    return $array; 
} catch (Exception $ex){ 
$array = [ 
    'status' => 0, 
    ]; 
    return $array; 
}} 

而且

function create_hashtag($dbh, $tagname) { 

try { 
$sql = 'INSERT INTO Hashtags (name) 
     VALUES (:name);'; 
$stmt = $dbh->prepare($sql); 
$stmt->bindParam(':name', $tagname); 
$stmt->execute(); 

$array = [ 
    'status' => 1, 
    ]; 
    return $array; 
} catch (Exception $ex){ 
$array = [ 
    'status' => 0, 
    ]; 
    return $array; 
} 
    //insert into Hashtags} 

編輯: 我用的var_dump以確保查詢工作。

//var_dump($pid); returns proper value 
preg_match_all("/\S*#(?:\[[^\]]+\]|\S+)/", $body, $matches); 
//for each loop array returned in matches 

//echo $matches['Array']; - why does this return "Array" 
//ISSUE with dimensionality of array 
foreach($matches['Array'] as $v){ 
    create_hashtag($dbh, $v); 
    attach_hashtag($dbh, $pid, $v); //inserts into tagged, 
} 
+0

foreach($ matches ['Array'] as $ v){ - 這應該給什麼?如果你不知道,陣列中有什麼,不要使用回聲。輸出$與var_dump或print_r匹配。 – Seb

+0

@Krpcannon我想幫助您找到解決此問題的解決方案。你可以做'var_export($ matches)',將數據發佈到你的問題,然後ping我? – mickmackusa

回答

0

我做了一些 「發明」 身體快速測試:

$body = 'fasd #has kfewf #tag lkfds #test 22 #fin'; 
preg_match_all("/\S*#(?:\[[^\]]+\]|\S+)/", $body, $matches); 
var_dump($matches); 

,其結果是:

array(1) { 
    [0]=> 
    array(4) { 
    [0]=> 
    string(4) "#has" 
    [1]=> 
    string(4) "#tag" 
    [2]=> 
    string(5) "#test" 
    [3]=> 
    string(4) "#fin" 
    } 
} 

所以你的$比賽[0]應該沒問題。現在你可以檢查,如果你的MySQL查詢是成功的?請檢查$ stmt-> execute()的返回值。如果它是錯誤的,那麼你的查詢有問題。

$result = $stmt->execute(); 
if ($!result) { 
    $error = $stmt->errorInfo(); 
    print_r($error); 
} 
+0

請參閱編輯。當我用var_dump測試$ matches數組時,它返回'array' – Krpcannon