1

I am creating a sitemap using XML. When I try to put multiple values to array, I am getting undefined index for the second variable.

Sample code below.

How I gather the results:

$tempArray = array();
switch ($type)
    {
case "v":
    $dbResult = $db->get_dbResult("Select title,id,vdate from " . DB_PREFIX . "tpV order by id desc " . this_offset($getFirstK));
    if ($dbResult)
        {
        foreach($dbResult as $pResult)
            {
            $tempArray[]['loc']   = convert_to_URL($pResult->id, $pResult->title);
            $tempArray[]['vdate'] = $pResult->vdate;
            }
        }

    break;

How I print the result.

array_filter($tempArray = array_map("unserialize", array_unique(array_map("serialize", $tempArray))));
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

foreach($tempArray as $tVars)
    {
    echo '<url>
<loc>
'.$tVars["loc"].'
</loc>
<lastmod>'.$tVars["vdate"].'</lastmod>
<changefreq>weekly</changefreq>
</url>';
    }
echo '</urlset>';

I am getting undefined index error for $tempArray[]['vdate']. Is there anything am I missing?

1
  • Try to var_dump your $tempArray before the foreach just to make sure you're having everything right. Commented Nov 28, 2016 at 10:13

2 Answers 2

1
$tempArray[]['loc']   = convert_to_URL($pResult->id, $pResult->title);
$tempArray[]['vdate'] = $pResult->vdate;

here you create two arrays, one with loc key, another with vdate, so one of the two keys must be undefined in the two arrys.

to fix this error, just change the two lines to

$tempArray[] = array('loc' => convert_to_URL($pResult->id, $pResult->title), 'vdate' => $pResult->vdate);

here is a demo

<?php
  $array=array();
  $array[]['a'] = 'a';
  $array[]['b'] = 'b';
  echo json_encode($array);

result:[{"a":"a"},{"b":"b"}]

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I see now, thank you for the clarification. Overthinking may cause embarrassment just as I had ^^
0

You can set Key.

$i = 0;
foreach($dbResult as $pResult)
{
            $tempArray[$i]['loc']   = convert_to_URL($pResult->id, $pResult->title);
            $tempArray[$i]['vdate'] = $pResult->vdate;
$i++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.