0

I want to combine two arrays but keeping the keys with digit order.

Here's the first array:

array:3 [▼
  0 => array:1 [▼
    "nombre" => "Pilsener"
  ]
  1 => array:1 [▼
    "nombre" => "Golden"
  ]
  2 => array:1 [▼
    "nombre" => "Suprema"
  ]
]

And here's the other array:

array:3 [▼
  0 => "6"
  1 => "5"
  2 => "1"
]

What i want is:

    array:3 [▼
      0 => array:1 [▼
        "nombre" => "Pilsener"
        "cantidad" => "6"
      ]
      1 => array:1 [▼
        "nombre" => "Golden"
        "cantidad" => "5"
      ]
      2 => array:1 [▼
        "nombre" => "Suprema"
        "cantidad" => "1"
      ]
    ]

I searched and found this but that didn't worked for me...

2 Answers 2

2

Since you don't have strings as keys you can't use array_merge_recursive(), but you could loop through the array and look if the key also exists in the other array and add the array to the other array, e.g.

foreach($arr2 as $k => $v){
    if(isset($arr1[$k]))
        $arr1[$k] = $arr1[$k] + ["cantidad" => $v];
}
Sign up to request clarification or add additional context in comments.

9 Comments

But, i would like an elegant way of doing it, i would use array_combine, but some names have spaces in the string, so i can't use them as key...
I've tried running this code and it doesn't work, unless I'm missing something?
@GluePear Just forgot to remove the index. Read OP's array output wrong.
@JonathanS. I don't get what you mean
@JonathanS. Your question includes what you want the expected result to be, and Rizier's answer gives you that result. You should accept his answer or ask a new question.
|
0

This is not a particularly elegant solution but it works:

$arr1 = [array('nombre'=>'Pilsener'),array('nombre'=>'Golden'),array('nombre'=>'Suprema')];
$arr2 = [6,5,1];

$new_array = [];

$i=0;

foreach($arr1 as $arr) {
    $temp_arr['nombre'] = $arr['nombre'];
    $arr['cantidad'] = $arr2[$i];
    $new_array[] = $arr;
    $i++;
}

1 Comment

Not bad, but i would prefer something shorter

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.