如何格式化数组

时间:2016-01-10 15:15:17

标签: php arrays

我试图将数据存储在数据库中的数组中。

打印完阵列后,我需要这样的东西:

Array ( [ABBA] => ?search=ABBA [ACDC] => ?search=ACDC [Ace of Spades] => ?search=AceOfSpades)

但是目前,我有这个:

Array ( [url] => ?search=ABBA [title] => ABBA ) Array ( [idtitle] => ?search=ACDC [title] => ACDC  ) Array ( [idtitle] => ?search=AceOfSpades [title] => Ace of Spades ) 

以下是我获取数据并存储到数组中的代码:

$key = $_POST['latestQuery'];

$requete = $bdd->prepare('SELECT url, title FROM articles WHERE title LIKE :key LIMIT 10');
$requete->execute(array('key' => '%'.$key.'%'));

$result_array[] = array();

foreach($requete->fetchAll(PDO::FETCH_ASSOC) as $search)
{
  print_r($result_array[$search['title']] = $search);
}

这是我的表结构:

url | title

$search=ACDC | ACDC

你认为有一种方法可以合成我的阵列吗?

2 个答案:

答案 0 :(得分:1)

print_r

中删除foreach
$result_array = array();
foreach($requete->fetchAll(PDO::FETCH_ASSOC) as $search)
{
    $result_array[$search['title']] = $search['url'];
}
print_r($result_array);

答案 1 :(得分:1)

你可以试试这个:

// testing array
$yourArray = array(
    array(
        'url'=>'?search=ABBA',
        'title'=>'ABBA',
        ),
    array(
        'url'=>'?search=BABA',
        'title'=>'BABA',
        ),
    array(
        'url'=>'?search=CBAA',
        'title'=>'CBAA',
        ),
    );

// solution
$myArr = array();
foreach ($yourArray as $key => $value) {
    $myArr[$value['title']] = $value['url'];
}

echo "<pre>";
print_r($myArr);

结果是:

Array
(
    [ABBA] => ?search=ABBA
    [BABA] => ?search=BABA
    [CBAA] => ?search=CBAA
)