Home » Php » php – Rename key of array

php – Rename key of array

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a table that I’m getting data from to output them. Table is consisted from bunch of personal data named as it follows – name, lastName, phoneNumber, email, birthYear, startedAt etc…

When I want to output the data inside my view on laravel, i fetch them without problem, but the things is, instead of writing each and every entry manually, i used loops. While using @foreach, I just get the name of the table column that I’ve previously appointed, so basically, when I output values, I get “name” instead of “Name, “lastName” instead of “Last Name” etc. Also, I have some column names with just 3 letters like “pro” that can mean thousand of things.

So, how do I rename those keys so my output should be human readable?

@foreach($data->getAttributes() as $key => $value)
   @if(!empty($value))
       <tr><td>{{ $key }}</td><td>{{ $value }}</td></tr>
   @endif
@endforeach
How to&Answers:

You need to have this name stored somewhere (i.e. in the database table) and retrieve it along with the collection.

A basic and possibly naive example of how to do this (without considering architectural best practices), for a table like:

CREATE TABLE data (
    ...
    name VARCHAR(255),
    nameText VARCHAR(255),
    content TEXT,
    ...

Where you had a record like:

[
    'name' => 'lastName',
    'nameText' => 'Last Name',
    'content' => 'This is your last name
]

You could have something like this in your controller:

$data = Model::get();
return view('my-view', ['data' => $data]);

Then in your view:

@foreach($data as $item)
    <tr><td>{{ $item->nameText }}</td><td>{{ $item->content}}</td></tr>
@endforeach

Answer:

There are two solutions for this. The first one is just simply using if else conditions inside your blade:

@foreach($data->getAttributes() as $key => $value)
    @if(!empty($value))
        @if($key === 'name')
            <tr><td>Name</td><td>{{ $value }}</td></tr>
        @elseif($key === 'lastName')
            <tr><td>Last Name</td><td>{{ $value }}</td></tr>           
        @else
            <tr><td>{{ $key }}</td><td>{{ $value }}</td></tr>
        @endif
   @endif
@endforeach

A different solution is to use CUSTOM PARTIALS for every single key.

Lets define custom partials for your keys:

// partials/display_data/name.blade.php
<tr><td>Name</td><td>{{ $value }}</td></tr>
// partials/display_data/lastName.blade.php
<tr><td>Last Name</td><td>{{ $value }}</td></tr>

Eventually, you can simply say:

@foreach($data->getAttributes() as $key => $value)
    @includeIf(!empty($value), "partials.custom_data.{$key}", compact('value'))
@endforeach