Tomazi
Tomazi

Reputation: 847

Add a string to multidimensional array

I have a function that returns an multidimensional array() I want to concatenate a string to every value of that array. How can I do this

for example my string:

$this->$string = 'helloAddMeToArray';

and my array is:

array(array('url' => 'PleaseAddAStringToMeIAmLonely'));

So i need my array value to be like this: helloAddMeToArrayPleaseAddAStringToMeIAmLonely

I tried concatenating these with '.' but does not allow me

Upvotes: 1

Views: 63

Answers (3)

KB9
KB9

Reputation: 609

Assuming your array could look like :

[
    "key"=>[
           "keyK"=>"val"
            ],
     "key2"=>"val2"
]

and you want to concatenate a string to every value from that array you should use array_walk_recursive function . This is a short snnipet doing this job :

$stringToConcatenate=$this->$string = 'helloAddMeToArray';
$callback($val,$key) use ($stringToConcatenate){
$val.=$val.$stringToConcatenate;
}
array_walk_recursive($youArray,$callback);

I hope it helps you .

Upvotes: 0

aftechie12
aftechie12

Reputation: 46

Try this:
First get string from your multidimentional Array, and type cast it.

$myString2 = (string)$myArray[0]->url;

Now use concatination: $string.$myString2;

Upvotes: 1

Mave
Mave

Reputation: 2514

$oldArray = array(array('url' => 'PleaseAddAStringToMeIAmLonely'));
$newArray = array();
$this->string = 'helloAddMeToArray';

foreach($oldArray as $o) {
 $newArray[] = array('url' => $this->string . $o['url']);
}

Upvotes: 2

Related Questions