'array_combine() expects parameter 2 to be array, string given in php

Array
(
    [0] => tttt
    [1] => tttt
)
$terms_keys = array("terms");
$terms_array = array();
foreach ( array_map(null,$inv_terms) as $key => $value ) {
    $terms_array[] = array_combine($terms_keys, $value);
}

what is mistake done in my code ?

php


Solution 1:[1]

The $value param in the foreach is of course not an array its a scalar tttt, so you could make it into an array by doing [$value] in the combine

$terms_keys = array("terms");
$terms_array = array();
foreach ( array_map(null,$inv_terms) as $key => $value ) {
    $terms_array[] = array_combine($terms_keys, [$value]);
}

Or simplified as the array_map() does not achieve anything

$terms_keys = array("terms");
$terms_array = array();
foreach ( $inv_terms as $key => $value ) {
    $terms_array[] = array_combine($terms_keys, [$value]);
}

Solution 2:[2]

I don't understand how it could be advantageous to bloat your array structure with more depth, but generating the indexed array of associative arrays can be done without iterated function calls. Just push the values into their new deep location using square-brace pushing syntax in a body-less foreach loop.

Code: (Demo)

$inv_terms = ['tttt', 'tttt'];
$result = [];
foreach ($inv_terms as $result[]['terms']);
var_export($result);

Output:

array (
  0 => 
  array (
    'terms' => 'tttt',
  ),
  1 => 
  array (
    'terms' => 'tttt',
  ),
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RiggsFolly
Solution 2 mickmackusa