1

I have an array whose schema is as follows:

            Array
(
[0] => stdClass Object
    (
        [text] => ans1
    )

[1] => stdClass Object
    (
        [text] => ans 2
    )

[2] => stdClass Object
    (
        [text] => ans3
    )

)

And, I wish to merge it so the result is as follows:

Array (ans1,ans2,ans3);

I know that I can loop over it to get that result, but is there a faster and ready made function to do this?

One more thing, if I wish to produce a string like the following:

$str = 'ans1,ans2,ans3';

what can i do?

slevy1
  • 3,797
  • 2
  • 27
  • 33
rahul singh
  • 451
  • 1
  • 3
  • 17
  • @MagnusEriksson array_merge wouldn't work on its own though cause the values all have the same key. – Loko Jul 13 '17 at 08:33
  • You need to loop through it and build the new array. When you have an array with just the texts, you can use [implode()](http://php.net/manual/en/function.implode.php) to create that string. – M. Eriksson Jul 13 '17 at 08:33
  • @Loko I read the question wrong at first. That's why I removed the comment. :-) – M. Eriksson Jul 13 '17 at 08:34
  • You just need to create an array with the values of stdClass Object, and it is not "merge" – Jigar Shah Jul 13 '17 at 08:35
  • 2
    It seems to me that it's a multi-dimensional array and he wants to create a single-dimensional array out of it. After that he wishes to convert the array to a string. – icecub Jul 13 '17 at 08:36
  • The string you can get with `implode` [(manual)](http://php.net/manual/en/function.implode.php): `$str=implode( ',' , array )`. To get the values in a single array, you have to loop teh original array and extract them. – Michel Jul 13 '17 at 08:36
  • yes, @icecub, it is like what you explained – Jigar Shah Jul 13 '17 at 08:37
  • @icecub Yes. you are right – rahul singh Jul 13 '17 at 08:37
  • There is no way of doing this without looping over it(I'm almost certain), since the values you want to merge are in the same array and it's a multidimensional array. – Loko Jul 13 '17 at 08:39
  • as per Esteban , we have a array_walk but isn't similar doing loop over array. – rahul singh Jul 13 '17 at 08:42
  • How do you get this array? I suspect you can make a small change upstream to get closer to the desired result. – axiac Jul 13 '17 at 09:15

2 Answers2

2

It is done by using array_column() in PHP7 or higher:

// in your Case, the Column-Key is "text"
$array = array_column($array, 'column-key');

The Function extracts Values from a determined Column into a new Array.

And the other Issue is done by imploding the Result of array_column() with implode():

$array = implode(',', $array);
Bernhard
  • 1,852
  • 11
  • 19
  • @rahulsingh I did some performance tests for you. `array_column() took 0.06 seconds on 10.000 runs` and `foreach() took 0.16 seconds on 10.000 runs`. So `array_column()` is definitely the best choice here. – icecub Jul 13 '17 at 09:14
  • 2
    You are almost there. Except it doesn't work in PHP 5 (`array_column()`). – axiac Jul 13 '17 at 09:15
  • @axiac `array_column()` seems to be working perfectly fine here on version 5.6.19? – icecub Jul 13 '17 at 09:35
  • 1
    @icecub Of course [`array_column()`](http://php.net/manual/en/function.array-column.php) works perfectly, even since PHP 5.5 when it was introduced, but it knows how to [handle objects](http://php.net/manual/en/function.array-column.php#refsect1-function.array-column-changelog) only starting with PHP 7.0. Take a look here: https://3v4l.org/Unt6T – axiac Jul 13 '17 at 09:53
  • 1
    Thanks for the Info. I adjusted my Answer. – Bernhard Jul 13 '17 at 10:59
0

The schema of the OP represents an array of objects (see here), each bearing a text property. With respect to the first question, I suggest using array_map(), as follows:

<?php

// create array of objects
$arr = [];
$tx = ["ans1","ans2","ans3"];

for ($i = 0, $max = 3; $i < $max; $i++) {
   $arr[] = new stdClass;
   $arr[$i]->text = $tx[$i];
}


//***** First Answer *******
$nu = array_map( function($e)
                 {
                    return $e->text;

                 }, $arr);

//***** Second Answer *******
$str = join(",",$nu);

// ***** Output *********
print_r( $nu );
print_r( $str );

See demo

array_map() does speedy, behind-the-scenes iteration as it applies an anonymous function, to each element of $arr. It returns a new array where each element contains the value of the text property of each stdClass object. While another respondent has suggested using array_column() which one may apply to a multidimensional array or an array of objects, unfortunately, it fails to handle an array of objects in PHP 5 (see here) unlike the capable array_map().

In answer to the second question, one may use join() to concatenate the $nu array values with a comma, as the example illustrates.

slevy1
  • 3,797
  • 2
  • 27
  • 33
  • I've did the numbers and here are the results: `array_column() took 0.06 seconds on 10.000 runs` -> `array_map() took 0.21 seconds on 10.000 runs`. The question was for the best and fastest solution. Even a plain old `foreach()` was faster than this. – icecub Jul 13 '17 at 09:24
  • php version: 5.6.19 ` – icecub Jul 13 '17 at 09:33
  • 1
    @slevy1 now its better! But before, there was no Explanation. It is imho important to add Explanations for less experienced Users. – Bernhard Jul 13 '17 at 09:39
  • Oh, I removed the `var_dump($nu);` part of course. Otherwise it would take a whole lot longer. – icecub Jul 13 '17 at 09:44