0

Whilst trying to transform multiple objects and put them into one array I unfortunately get a array-in-array result.

The objects I would like to transform:

array(2) {
  [0]=>
  object(stdClass)#104 (1) {
    ["name"]=>
    string(4) "Paul"
  }
  [1]=>
  object(stdClass)#105 (1) {
    ["name"]=>
    string(5) "Jenna"
  }
}

My PHP:

for ($i=0; $i < count($readers) ; $i++) {
    $json = json_encode($readers[$i]);    // 1          

    $data = json_decode($json, TRUE);     // 2    

    $arr = array();
    array_push($arr, $data);              // 3
}

The outputs:

// 1
{"name":"Paul"}{"name":"Jenna"}

-

// 2
Array
(
    [name] => Paul
)
Array
(
    [name] => Jenna
)

-

// 3
Array
(
    [0] => Array
        (
            [name] => Paul
        )

)
Array
(
    [0] => Array
        (
            [name] => Jenna
        )

)  

Desired Outcome

I would like to have everything merged into one array. The key is the index and the value is the name.

Array
(
    [0] => Paul
    [1] => Jenna
)

3 Answers 3

1

Loop through the array of objects ($arr) and compile the final array ($finArr) with the $val->string value. Try this:

$finArr = array();
foreach ($arr as $key => $val) {
  $finArr[] = $val->string;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply iterate through the array of readers, pull out the name of each reader, and add each of their names to a numerically indexed array as you desire.

$names = array(); // Initialize.

foreach($readers as $reader) {
    if (!empty($reader->name)) {
        $names[] = $reader->name;
    }
}

print_r($names); // To see what you've got.

Array
(
    [0] => Paul
    [1] => Jenna
)

Comments

1

You have to extract key also from array. And declare $arr = array() outside foreach

$arr = array();
for ($i=0; $i < count($readers) ; $i++) {
    $data = $readers[$i]->name;          //change this line 
    array_push($arr, $data);              // 3
}

print_r($arr);

Another way is you can simply use array_column()

$arr = array_column($readers,"name");
print_r($arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.