#php #arrays
#php #массивы
Вопрос:
Я изучаю PHP, и я борюсь с массивами. Я пытаюсь объединить два массива вместе, но объединить их данные вместе вот так.
Массив $instruction1 содержит имена инструкций рецепта.
[0] = Prep
[1] = Cook
[2] = Serve
Второй массив содержит инструкции относительно того, что вы делаете при приготовлении, приготовлении и подаче.
[0] = In a large mixing bowl, crack 2 large eggs.
[1] = In a medium-sized frying pan or griddle, heat up a tablespoon of unsalted butter...
[2] = When done, transfer the french toast onto a plate.
Когда я объединяю два массива, я получаю
[0] = Prep
[1] = Cook
[2] = Serve
[3] = In a large mixing bowl, crack 2 large eggs.
[4] = In a medium-sized frying pan or griddle, heat up a tablespoon of unsalted butter...
[5] = When done, transfer the french toast onto a plate.
Вот фактический результат.
(
[0] => Array
(
[0] => Array
(
[name] => One
)
[1] => Array
(
[name] => Two
)
[2] => Array
(
[name] => Three
)
[3] => Array
(
[text] => In a large mixing bowl, crack 2 large eggs. Season with a dash of salt. Whisk thoroughly. Pour 2 cups of fresh milk (2%, non-fat or whole milk) and a tablespoon of honey. Whisk again until well combined. 2. Slice or get a slice of bread and dip into the milk and egg mixture. Soak for 30seconds.
)
[4] => Array
(
[text] =>
In a medium-sized frying pan or griddle, heat up a tablespoon of unsalted butter over medium heat until it melts completely. Put the soaked bread and toast it for 3-5 minutes or until golden. Pour 1/4 cup of the mixture. Push the excess liquid to the center and onto the bread. Check the bread every 30-60 seconds. Flip the bread over and toast the other side for equal time
)
[5] => Array
(
[text] =>
When done, transfer the french toast onto a plate. Top with your choice of fruits, with powdered sugar, butter, or Nutella. Then drizzle with your favorite maple syrup. Serve warm and enjoy!!
)
)
)
Вот чего я надеюсь достичь.
Array
(
[0] => Array
(
[@type] => HowToStep
[name] => prep
[image] => some image link
[text] => In a large mixing bowl, crack 2 large eggs. Season with a dash of salt. Whisk thoroughly. Pour 2 cups of fresh milk (2%, non-fat or whole milk) and a tablespoon of honey. Whisk again until well combined. 2. Slice or get a slice of bread and dip into the milk and egg mixture. Soak for 30seconds.
)
[1] => Array
(
[@type] => HowToStep
[name] => cook
[image] => some image link
[text] =>
In a medium-sized frying pan or griddle, heat up a tablespoon of unsalted butter over medium heat until it melts completely. Put the soaked bread and toast it for 3-5 minutes or until golden. Pour 1/4 cup of the mixture. Push the excess liquid to the center and onto the bread. Check the bread every 30-60 seconds. Flip the bread over and toast the other side for equal time
)
[2] => Array
(
[@type] => HowToStep
[name] => serve
[image] => some image link
[text] =>
When done, transfer the french toast onto a plate. Top with your choice of fruits, with powdered sugar, butter, or Nutella. Then drizzle with your favorite maple syrup. Serve warm and enjoy!!
)
)
Мой код
$explod1 = saswp_explod_by_semicolon($all_post_meta['saswp_recipe_instructions_name'.$schema_id][0]);{
foreach ($explod1 as $val1)
$instruction1[] = array('name'=>$val1);
// print_r ($instruction1);
}
$explod = saswp_explod_by_semicolon($all_post_meta['saswp_recipe_instructions_'.$schema_id][0]);
// $test = array_push ($explod,$explod1);
foreach ($explod as $val)
// foreach ($explod1 as $val1)
{
$instruction[] = array('text'=>$val);
// array_unique ($instruction);
}
$test1[] = array_merge($instruction1,$instruction);
print_r ($test1);
}
Надеюсь, вы, ребята, сможете помочь. Я потратил более 12 часов, пытаясь разобраться в этом. Чтение и обучение.
Комментарии:
1. 1. пожалуйста, покажите нам свои php-коды (чтобы мы знали, в каких частях есть / есть проблемы)
Ответ №1:
я думаю, что у вас одинаковая длина для всего массива для шагов и инструкций здесь вам нужно сохранить эти два массива в другом массиве с конкретными элементами этого массива с тем же ключом
//array that contain steps
$array1=array('Prep','Cook','Serve');
//array that contain instructions
$array2=array('In a large mixing bowl, crack 2 large eggs.','In a medium-sized frying pan or griddle, heat up a tablespoon of unsalted butter...','When done, transfer the french toast onto a plate.');
//calculate length of any one array because length is same
$length=count($array1);
//store that particular element in new array with keys
$array3=array();
for($i=0;$i<$length;$i ){
$array3[$i]['name']=$array1[$i];
$array3[$i]['text']=$array2[$i];
//you can add that another key and value here like $array3[$i]['image']='your image link';
}
//print the final array
echo '<pre>';
print_r($array3);
Комментарии:
1. Спасибо, Акшай! Я попробую это завтра и дам вам знать. Я действительно ценю, что вы нашли время, чтобы помочь мне с этим.
2. Асхай, прими мою огромную благодарность! То, что вы мне дали, сработало как шарм. Я действительно ценю вашу помощь.
Ответ №2:
$combined = array_merge($instruction1, $second);
Комментарии:
1. смотрите также
array_merge_recursive
,array_replace
иarray_replace_recursive