Yudhistira Muslim
Yudhistira Muslim

Reputation: 163

How to insert array to array PHP

I have arrays, I don't know how to fix I already try array_push, array_combine, array_merge, but still nothing.

$distance = array(3) {
  [0]=>
  float(2.2)
  [1]=>
  float(1.1)
  [2]=>
  float(3.9)
}
$getID = array(3) {
  [0]=>
  string(1) "B"
  [1]=>
  string(1) "C"
  [2]=>
  string(1) "F"
}

I want to

array(3) {
  [0]=> ["B", 2.2]
  [1]=> ["C", 1.1]
  [2]=> ["F", 3.9]
}

this is my code

function mergeArray($distance, $getID)
{
    $mergeArray = array();
    for ($i = 0; $i < count($distance); $i++) {
        $mergeArray[] = array_splice($getID, $distance[$i]);
    }
    return $mergeArray;
}

Edited help me please thx

Upvotes: 0

Views: 785

Answers (4)

Raby&#226; Raghib
Raby&#226; Raghib

Reputation: 154

For your current code to work you have to:

  • pass both elements to array_splice function as an array
  • pass the offset of where the function need to replace the value
  • as well as the number of how many elements should be removed
  • You should not reassign $mergeArray because array_splice work with pointer

Checkout the docs for more!

function mergeArray($distance, $getID)
{
    $mergeArray = [];
    for ($i = 0; $i < count($distance); $i++) {
        array_splice($mergeArray,$i,1, [[
             $distance[$i],
             $getID[$i]
        ]]);
    }
    return $mergeArray;
}

however a better approach is to do as in M. Eriksson's ansewar.

Upvotes: 0

Elias Soares
Elias Soares

Reputation: 10254

You can use array_map to iterate over two arrays simultaneously and produce a new array:

$distance = array(3) {
  [0]=>
  float(2.2)
  [1]=>
  float(1.1)
  [2]=>
  float(3.9)
}
$getID = array(3) {
  [0]=>
  string(1) "B"
  [1]=>
  string(1) "C"
  [2]=>
  string(1) "F"
}

$output = array_map(function ($d, $id) {
    return [$id, $d];
}, $distance, $getID);

Note that this code assumes that both arrays have the same length.

Offtopic:

A little advice about your code: always name your variable with something that allows you to know what's inside it, using correct plural too:

Your $distance variable contains an array off distances, so it nsme should be in plural.

Your $getID is not a function, so it should not be called get, but just $Ids instead.

Upvotes: 1

lukas.j
lukas.j

Reputation: 7163

$distance = [ 2.2, 1.1, 3.9 ];
$getID = [ "B", "C", "F" ];

$result = array_map(fn(string $id, float $distance) => [ $id, $distance ], $getID, $distance);

print_r($result);

Upvotes: 0

M. Eriksson
M. Eriksson

Reputation: 13635

You don't need "array_combine()", "array_slice()" or similar. Just iterate through the data and create a new one:

$a = [2.2, 1.1, 3.9];
$b = ["B", "C", "F"];

$new = [];
foreach ($a as $index => $value) {
    $new[] = [
        $b[$index], // Fetch the value with the same index from the other array
        $value
    ];
}

Demo: https://3v4l.org/oseSV

Upvotes: 2

Related Questions