emmab
emmab

Reputation: 5

Ignore element where a value name does not exist in PHP multidimensional array

Sorry if using wrong terms below, hopefully you understand what I mean. Also, please note this is just a learning task and not actually used.

I have some JSON data which has been imported and decoded into an array. The array is about 20 elements of different products for a webshop which has multiple values (id,name,price,stock,category,discount etc). I want to print a list of all the items based on name. However, one of the elements does not have a name. The "name":"" is completely missing in the JSON data, therefore in my array too. So, it's not NULL, it just doesn't exist.

I have tried various of if functions (isset, !empty) and put usort and foreach inside the if loop, but I believe those I've tried demand that the certain value name actually exists but is not set and not that it is not there at all.

Code example to print list:

echo "<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>";
                        
            usort($product_data, fn($a,$b) => strcmp($a->name, $b->name) );
            foreach($product_data as $product) { 
            echo "<tr>";
            echo "<td>". $product->name ."</td>";
            echo "<td>". $product->price ."</td>";
            }
        }
            echo"</td>
            </tr>
    </tbody>
    </table>";

I get this error no matter what I do: Notice: Undefined property: stdClass::$name in [filename]

I'm thinking there must be a quick way to say "if 'name' exists do this (otherwise nothing)" but cannot find it at all. Please help!

Upvotes: 0

Views: 850

Answers (2)

Mark
Mark

Reputation: 11

What about $product->name ?? '';

It's like isset($product->name) ? $product->name : '';

Upvotes: 1

Ammar Dje
Ammar Dje

Reputation: 90

solution may be

<pre>if(property_exists($product, 'name')){
 //put here your td
 echo "<td>". $product->name ."</td>";

}</pre>

use property_exists(object,attribtue betwen quotation) for checking if each attribute that you are fetching exist

Upvotes: 0

Related Questions