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);
5
  • 3
    The first line is not neccessary. Commented Jan 24, 2014 at 6:15
  • 3
    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. Commented Jan 24, 2014 at 6:16
  • 4
    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 Commented Jan 24, 2014 at 6:17
  • 3
    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. Commented Jan 24, 2014 at 6:18
  • Fixed for associative array Commented Jan 24, 2014 at 6:19
1

Just Try.

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

in for loop

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

print_r($arrayvalues);

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.