8795 sujets

Développement web côté serveur, CMS

$master-array = Array (
	[title] => The Night of the Hunter
	[year] => 1955
	[box-office] =>
	[produced] => United Artists
	
	[mpaa] => Array (
		[rating] =>
		[locale] => USA
		[reason] =>
	)
	
	[plot-summary] => ...The Night of the Hunter is now regarded as a classic.
	[plot-summary-author] => Hal Erickson
	[runtime-min] => 93
	
	[genre] => Array (
		[0] => Thriller 
		[1] => Crime Thriller
		[2] => Psychological Thriller
		
	)
)


Hello ! Je voudrais transformer cet array pour obtenir ceci :

$master-array = Array (
	[master-array-title] => The Night of the Hunter
	[master-array-year] => 1955
	[master-array-box-office] =>
	[master-array-produced] => United Artists
	
	[master-array-mpaa-rating] =>
	[master-array-mpaa-rating] => USA
	[master-array-mpaa-rating] =>

	
	[master-array-plot-summary] => ...The Night of the Hunter is now regarded as a classic.
	[master-array-plot-summary-author] => Hal Erickson
	[master-array-runtime-min] => 93
	
	[master-array-genre-0] => Thriller 
	[master-array-genre-1] => Crime Thriller
	[master-array-genre-2] => Psychological Thriller
)


Mais je me casse les dents, entre les foreach, les keys... c'est vraiment dur !
J'ai trouvé une fonction qui aide, mais je coince pour le "dé-parentage" et la nomenclature des clés.
Merci pour votre aide !

function array_push_associative(&$arr)
{
  foreach (func_get_args() as $arg)
  {
    if (is_array($arg))
      foreach ($arg as $key => $value) { $arr[$key] = $value; $ret++; }
    else
      $arr[$arg] = '';
  }

  return $ret;
}


(s'utilise comme ça Smiley smile

$unique_item = array($key => $value);
$new_data_full = array_push_associative($new_data_full, $unique_item);

Modifié par gordie (15 Nov 2007 - 12:51)
ok,
function flatten($current, &$result, $key) {
  foreach($current as $k=>$v) {
    if ( is_array($v) ) {
      flatten($v, $result, $key.'-'.$k);
    }
    else {
      $result[$key.'-'.$k] = $v;
    }
  }
}

	$new_data_full=array();
	flatten($data_full, $new_data_full, 'master');

Bonjour,

Il faut que ta fonction s'appelle elle-même (récursivité)

Voilà la manière que j'utiliserai
function array_push_recursive(&$output, $input, $parent='') {
	if(!is_array($input) || !is_array($output)) {
		trigger_error('Les deux premiers arguments de la fonction doivent être des tableaux', E_USER_WARNING);
		return false;
	}

	foreach ($input as $key => $value) {
		$key = (string) $key;
		if(is_array($value))
			array_push_recursive($output, $value, $parent.$key.'-');
		else 
			$output[$parent.$key] = $value;
	}
	return;
}