-1

I am trying to decode json and then break the value with foreach loop. Here is my script.

 <?php $new_data=json_decode($pay_data->l1_level,true);
                      print_r($new_data);
                     ?>

this print return array.

Array ( [name] => Array ( [0] => sanjay [1] => susanchen [2] => mabelzhen) [product-price] => Array ( [0] => 250 [1] => 250 [2] => 250) )

I am trying to break this foreach loop and get name and price value . I am trying to this away

foreach($new_data as $value){
echo $value->name;
echo $value->product_price ;
}

But This is not working.Any Help will be Appreciate.

Sanjay Yadav
  • 243
  • 3
  • 20
  • it's inside another dimension, so if you want to reach out `name`, you'd need to directly point to it `foreach ($new_data['name'] as $v)`, and same for the price. if you need to iterate on the whole thing, just add another foreach inside `foreach ($new_data as $value) { foreach ($value as $v) }` like so – Kevin Apr 16 '21 at 02:39
  • Kevin , I can not irritate whole thing . I have to put these thing in html table so I am breking this key and value. please help to get this as key and value – Sanjay Yadav Apr 16 '21 at 02:45
  • Does this answer your question? [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – El_Vanja Apr 16 '21 at 10:13
  • You're mixing up array and object access. See the proposed duplicate for examples on how to handle either. – El_Vanja Apr 16 '21 at 10:14

1 Answers1

0

When you use foreach($new_data as $value), the $value doesn't have the key.

Please try the following code.

    foreach($new_data as $value){
        print_r($value);
    }

the result is Array ( [0] => sanjay [1] => susanchen [2] => mabelzhen ) Array ( [0] => 250 [1] => 250 [2] => 250 )

Wizard
  • 51
  • 6
  • Wizard@ Hey I need this value to put in echo $value->name. please let me know how can list the all value in coulumn – Sanjay Yadav Apr 16 '21 at 03:03
  • In PHP, ->, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here. // Create a new instance of MyObject into $obj $obj = new MyObject(); // Set a property in the $obj object called thisProperty $obj->thisProperty = 'Fred'; – Wizard Apr 16 '21 at 04:43
  • $new_data is an Array. So print_r( $new_data["name"]); will show the "name" array. – Wizard Apr 16 '21 at 04:44
  • wizard then how can get object data of this $new_data["name"] – Sanjay Yadav Apr 16 '21 at 04:54
  • $new_data["name"] is also an Array. if you want to get object data, you have to make a new object. At first, you have to define Class to create your object. https://www.w3schools.com/php/php_oop_classes_objects.asp You can find how to define class and make a object. – Wizard Apr 16 '21 at 05:08