Manu Shioyaki
Manu Shioyaki

Reputation: 51

Mapping function for an array

I have an array like this $a=("something","something else","another something"); and another array like this $b=("b","bb").

I would like to produce an $a = array("something"=>Array("b","bb"),"something else","another something");. How can achieve this?

Upvotes: 1

Views: 741

Answers (3)

New Alexandria
New Alexandria

Reputation: 7324

Try array_map for more flexibility:

function map_a_thing(key, val, compare) {
  if (key == compare)
    return array(key => val);
  else
    return key;
  end
}

$c = array_map('map_a_thing', $a, $b, 'something');

Consider that you're essentially asking a map-reduce question, where you seek a function to perform a given action upon a condition.

With this answer, you could iterate over your base array and re-map certain values

$map_targets = array('something', 'some2', 'some45', 'some-other');
foreach ($map_targets as $target) {
    $a = array_map('map_a_thing', $a, $b, $target);
}

See also, array_reduce, array_filter, and the generic array_walk

Upvotes: 1

NullPoiиteя
NullPoiиteя

Reputation: 57322

try this, there area many option either you can do this on the basis of the position or by the array element like the @Mike Moore answers

$a = array ( 'something', 'something else',  'another something');

$b = array('b', 'bb');

for($i = 0; $i < count($a); $i++)
{
    if($i==0)
    {
        $a[$i] = array('something' => $b);
    }
}


print_r($a);

Upvotes: 1

Mike Moore
Mike Moore

Reputation: 7468

YIKES my old answer was crap. Thanks for pointing it out everybody!

Here is my updated answer:

<?php

$a = array (
    'something',
    'something else',
    'another something'
);

$b = array('b', 'bb');

for($i = 0; $i < count($a); $i++)
{
    if($a[$i] == 'something')
    {
        $a[$i] = array('something' => $b);
    }
}


print_r($a);

Upvotes: -1

Related Questions