-1

次のコードは、検索エンジンからの URL、タイトル、およびスニペットに関連付けられた配列を返し、正常に動作します。

$js = json_decode($data); 

    $blekkoArray = array();                     

    $find = array ('http://','https://','www.');

    foreach ($js->RESULT as $item)
    {   
        $blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );         
        $blekkoArray[$i]['title'] = ($item->{'url_title'});
        $blekkoArray[$i]['snippet'] = ($item->{'snippet'});
        $i++;
    }

    print_r ($blekkoArray);

たとえば、各要素をスコアリングできるように、配列に別の値を追加しようとしています。最初の結果のスコアを 100、2 番目の結果を 99、3 番目の結果を 98 などにしたい場合、次のコードは上記と同じように吐き出します。したがって、配列に「スコア」を追加することはできないようです。よろしく

$js = json_decode($data); 

    $blekkoArray = array();                     

    $find = array ('http://','https://','www.');

    foreach ($js->RESULT as $item)
    {   
        $score = 100;
        $blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );         
        $blekkoArray[$i]['title'] = ($item->{'url_title'});
        $blekkoArray[$i]['snippet'] = ($item->{'snippet'});
        $blekkoArray[$i]['score'];
        $i++;
        $score--;
    }

    print_r ($blekkoArray);
4

2 に答える 2

1

あなたは2つの間違いを犯しました。

1) $scoreforeach ループ内で初期化しました。外部にある必要があります。そうしないと、常に $score = 100 になります。

2) 配列に $score を割り当てていません。

$score = 100; // move the initialization of $score outside of loop
foreach ($js->RESULT as $item)
{           
    $blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );         
    $blekkoArray[$i]['title'] = ($item->{'url_title'});
    $blekkoArray[$i]['snippet'] = ($item->{'snippet'});
    $blekkoArray[$i]['score'] = $score;      // assign the $score value here
    $i++;
    $score--;
}

またはu_mulderによって提案された

$blekkoArray[$i]['score'] = $score--;
于 2013-07-20T12:43:26.813 に答える
1

$score = 100;foreach 配列の外側を持ってきます。ループごとに100にリセットしています。そして使う

$blekkoArray[$i]['score'] = $score--;

または2行で同じ:

$blekkoArray[$i]['score'] = $score;
$score--;

ついでに、キーはforeachで使えないの?このような?これは、どうなるか分からないのであくまで推測です$i。あなたのコードでは定義も初期化もされていないので...そしてちょっとしたおまけの変更: フィールド名として変数を使用していない場合は、$var->{'fieldname'}表記を に簡略化できます$var->fieldname

まとめると、次のコードが得られます。

$score = 100;
foreach ($js->RESULT as $i => $item)
{
    $blekkoArray[$i]['url'] = str_replace ($find, '', $item->url);
    $blekkoArray[$i]['title'] = $item->url_title;
    $blekkoArray[$i]['snippet'] = $item->snippet;
    $blekkoArray[$i]['score'] = $score--;
}
于 2013-07-20T12:44:34.620 に答える