0

i have this code

for ($x = 0; $x <= count($testas); $x += 2) {

    $object = new stdClass();
    $object->$testas[0] = $x;
    $newArr[] = $object;
    }

echo json_encode($newArr);

everything works well here, but if i chagne $testas array like this:

for ($x = 0; $x <= count($testas); $x += 2) {

    $object = new stdClass();
    $object->$testas[$x] = $x;
    $newArr[] = $object;
    }

echo json_encode($newArr);

it doesnt print out anything. Please help

Thanks

7
  • 1
    What are you actually trying to do? It's not usual for loop. Commented Oct 29, 2015 at 9:52
  • i have an array say like this: $array = array ('a', 'b', 'c', 'd'); And i want it to print a json that it would be like this: [{"a":"d"},{"c":"d"} Commented Oct 29, 2015 at 10:03
  • What does it mean: $x += 2? Commented Oct 29, 2015 at 10:03
  • Why count($testas) (just variable) but $object->$testas[$x] (object property). Are that the same array or not? Commented Oct 29, 2015 at 10:04
  • i have an array say like this: $array = array ('a', 'b', 'c', 'd'); And i want it to print a json that it would be like this: [{"a":"d"},{"c":"d"} Commented Oct 29, 2015 at 10:05

1 Answer 1

1

Looks like that you want. Odd elements become properties, event elements become values of the key-value objects. And that objects are in one array.

It's better for me to wrap variable object field name in curly braces. Just not to be messed up with that.

$testas = array ('a', 'b', 'c', 'd');
$newArr = array();

for ($x = 0; $x < count($testas); $x += 2) {

     $object = new stdClass();
     $object->{$testas[$x]} = $testas[$x + 1];

     $newArr[] = $object;
}

echo json_encode($newArr);

Output is:

[{"a":"b"},{"c":"d"}]

Sign up to request clarification or add additional context in comments.

2 Comments

i dont know what you did here because i had the same code but i works, thanks
May be your other code is not the same as mine. You provided just part of your code. Check other code carefully.

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.