PHP将所有数组键更改为相同的值

时间:2017-12-19 13:27:54

标签: php arrays loops key

我有3个数组,它们的值来自之前执行的循环。结果如下:

1。我在print_r

时变量
Array
(
[0] = some title
[1] = some title
[2] = some title
[3] = some title
)

2。我在print_r

时变量
Array
(
[0] = some id
[1] = some id
[2] = some id
[3] = some id
)

第3。我在print_r

时变量
Array
(
[0] = some image
[1] = some image
[2] = some image
[3] = some image
)

现在我希望每个数组都有自己的密钥,所以我可以将它们组合起来并得到这个结果:

结果

 Array
    (
    [0]=> Array
          (
           [Title] = title
           [Id] = id
           [Image] = image
     )
    [1]=> Array
          (
           [Title] = title
           [Id] = id
           [Image] = image
     )
    [2]=> Array
          (
           [Title] = title
           [Id] = id
           [Image] = image
     )
    )

我试图在循环时给出键,但在循环外我只得到一个结果。这是一个例子:

 $imgSource = array();

foreach($lists as $list) {
 $tmp_dom->appendChild($tmp_dom->importNode($list,true));
 $all_images = $list->getElementsByTagName('img');
  foreach ($all_images as $image) {
   if ($image->hasAttribute('src')) {
    $imgSource['Title'] = $image->getAttribute('src');
   }
   if ($image->hasAttribute('data-lazy-src')) {
    $lazyImageSource['Title'] = $image->getAttribute('data-lazy-src');
   }
  }
 }
}
print_r($imgSource);
print_r($lazyImageSource);

如果没有钥匙,我会按照我之前展示的方式获得所有元素(1. - 3.变量)

之后我有了这个:

$combined = array_merge($uber, $nodes );
array_push($wohnungen, $combined);

这应该给出我想要的结果,但没有键,它只是一个接一个地添加数组:

Array
    (
    [0] = some title
    [1] = some title
    [2] = some title
    [3] = some title
    [4] = some id
    [5] = some id
    [6] = some id
    [7] = some id
    [8] = some image
    [9] = some image
    [10] = some image
    [11] = some image
    )

我希望我足够彻底。如果您有任何问题,请随时提出,以便我可以编辑问题。

提前致谢

1 个答案:

答案 0 :(得分:5)

$newArray = array();
for($i=0; $i<count($firstArray);$i++)
{
 $newArray[] = array('Id'=> $firstArray[$i],
                     'Title'=> $secondArray[$i],
                     'Image'=> $thirdArray[$i]);
}

$newArray有你需要的东西。