4532066
4532066

Reputation: 2110

Accessing specific element in FETCH_ASSOC array using numeric reference

I have a simple example here of using FETCH_ASSOC:

// array 1
$sql1 = "SELECT shortname, unicode FROM my_table ORDER BY RAND() LIMIT 4";
$stmt1 = $pdo->prepare($sql1);
$stmt1->execute();
$data1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);

// array 2
$sql2 = "SELECT shortname, unicode FROM my_table ORDER BY RAND() LIMIT 4";
$stmt2 = $pdo->prepare($sql2);
$stmt2->execute();
$data2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);

Loop through the first array:

$counter = 0;

foreach($data1 as $item) {

    // get items from table
    $shortname = $item['shortname'];
    $unicode = $item['unicode'];

}

I can see my checking the format of the $data1 array that it looks like this:

Screenshot of example array data

I can use the foreach loop to loop through the first array.

Each time through the loop, I want to access the corresponding values from the other array (in $data2).

I'm stuck working out the syntax to be able to reference a specific shortcode and unicode pairing from the array.

For example, how would I reference the data in the 3rd element, e.g. "heart" and "2764"? I think I need to pass the number 2 in somehow, to say I want to access the data in the 3rd element, but I'm not sure how?


Thanks to help from arkascha below, I got the answer as:

// array 1
$sql1 = "SELECT shortname, unicode FROM my_table ORDER BY RAND() LIMIT 4";
$stmt1 = $pdo->prepare($sql1);
$stmt1->execute();
$data1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);

// array 2
$sql2 = "SELECT shortname, unicode FROM my_table ORDER BY RAND() LIMIT 4";
$stmt2 = $pdo->prepare($sql2);
$stmt2->execute();
$data2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);

$counter = 0;

foreach($data1 as $item) {

    // get data from $data1
    $shortname1 = $item['shortname'];
    $unicode1 = $item['unicode'];

    // get data from $data2 by referincing them using $counter value
    $shortname1 = $data2[$counter]['shortname'];
    $unicode1 = $data2[$counter]['unicode'];

    // build the values from above into a concatenated HTML string to output later on...

    // increment the counter
    $counter ++;

}

Upvotes: 1

Views: 418

Answers (1)

Hamed Ghaderi
Hamed Ghaderi

Reputation: 98

As you fetch the result from the DB and you don't know in which index 'heart' and '2764' exists, you can use this technique to find the index.

$inde = array_search('2764', array_column($data1, 'unicode'));

This code returns the index where 'heart' and '2764' exsists.

Now, you can access these values using $data1[$key];

Upvotes: 1

Related Questions