如何更改关联数组中的命名关键点


How can I change the named keys in an associative array

以下代码返回如下所示的关联数组

Array ( [1] => Array ( 
   [url] => example.com
   [title] => Title.example
   [snippet] => snippet.example 
) )
$blekkoArray = array();                     
    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);

我如何修改数组,使数组元素不是由1,2,3等标识的,而是由url(例如)标识的

Array ( [example.com] => Array ( 
   [title] => Title.example
   [snippet] => snippet.example 
) )

您也可以尝试这个(单线解决方案)

$newArray = array( $old[0]['url'] => array_splice($old[0], 1) );

演示

其他解决方案似乎专注于在之后更改阵列

foreach ($js->RESULT as $item)
    {   
        $blekkoArray[str_replace ($find, '', ($item->{'Url'}))] = array(         
        'title'=> $item->{'url_title'},
        'snip pet' => $item->{'snippet'}
         );
    }

这应该使数组成为您需要的

非常简单,只需使用url而不是$i

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

考虑您的示例如下。其中$js是您想要修改的数组。

$js = array( 
    1 => array ( 'url' => 'example.com', 'title' => 'Title.example','snippet' => 'snippet.example'), 
    2 => array ( 'url' => 'example2.com', 'title' => 'Title.example2','snippet' => 'snippet.example2'),
    3 => array ( 'url' => 'example3.com', 'title' => 'Title.example3','snippet' => 'snippet.example3'));
$blekkoArray = array();   
// The lines below should do the trick
foreach($js as $rows) { // main loop begins here
    foreach($rows as $key => $values) { // access what's inside in every $row by looping it again
        if ($key != 'url') {
             $blekkoArray[$rows['url']][$key] = $values; // Assign them
        }        
    }
}
print_r ($blekkoArray);

$js数组中有多少元素并不重要,因为它每次只会重复这个过程。

foreach ($arr as $key => $value){
    $out[$value['url']] = array_slice($value, 1);
}