2

I have an array of php objects that looks like

array(3) {
  [0] object(stdClass)#153 (2) {
    ["key"] "a"
    ["val"] "2"
  }
  [1] object(stdClass)#154 (2) {
    ["key"] "b"
    ["val"] "2"
  }
  [2] object(stdClass)#155 (2) {
    ["key"] "c"
    ["val"] "5"
  }
}

and I want to turn it into this

array(3) {
  ["a"] 2
  ["b"] 2
  ["c"] 5
}

I've tried some variations of foreach loops but can't quite figure it out because of each value of the original array being an object with two keys. How can I clean this up and get it into a straight array?

3 Answers 3

3
$newArray=array();
foreach($yourObjects as $obj)
{
 $newArray[$obj->key]=$obj->val;
}
print_r($newArray);
Sign up to request clarification or add additional context in comments.

5 Comments

The first line is not neccessary.
It is necessary for any good code. That $newArray might be a duplicate name of something up in the code, it can lead to unexpected behavior, it can make it difficult to understand, so on and so forth. It is one of the bad things with PHP that it allows programmers to work with variables without even declaring them first.
It's not necessary, but very welcome : initializing your variables is a good habit. It may save a lot of debugging time. Btw: OP wants associative array
There are a lot of things that are not necessary, but important. Indentation is one example, its not necessary but any code without it makes life tough.
Fixed for associative array
1

Just Try.

$array=array();
foreach($obj as $objVal)
{
 $array[$objVal->key]=$objVal->val;
}
    echo "<pre>";
     print_r($array);
    echo "</pre>";

Comments

0

in for loop

$arrayvalues=array();
for($i=0;$i<count($yourobject);$i++)
{
 $arrayvalues[]=$yourobject[$i]->val;
}

print_r($arrayvalues);

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.