skip to Main Content

I have a simple question, I did it in javascript, but in php everything is different:
In my request when I did dd($request->all()) it returned an array like this

$request = [
  'question_ru' => 'question ru',
  'asnwer_ru' => 'answer ru',
  'question_uz' => 'question uz',
  'asnwer_uz' => 'answer uz',
  'question_en' => 'question en',
  'asnwer_en' => 'answer en',
];

Now my problem is, I need to write a function which gets two argument: 1) a request, 2) a key and returns an array like this

function filter_array_by_key($array, $key) {}

function filter_array_by_key($request, 'title') =>

$result = [
  'title' => [
    'ru' => 'question ru',
    'uz' => 'question uz',
    'en' => 'question en',
  ],
];

‘JS VERSION’

export function filterFormDataByKey(object: Object, key: string) {
  let startNumber = key.length + 1
  const data = lodash.entries(object)

  let filteredObject = {}

  data.forEach((arr) => {
    if (arr[0].startsWith(key)) {
      let innerObj = { [arr[0].slice(startNumber)]: arr[1] }

      Object.assign(filteredObject, innerObj)
    }
  })

  return filteredObject
}

and it worked well!

2

Answers


  1. function filter_array_by_key($array, $key) {
        $result = [];
        foreach ($array as $arrayKey => $value) {
            if (strpos($arrayKey, $key) === 0) {
                $langCode = substr($arrayKey, strlen($key) + 1);
                $result[$key][$langCode] = $value;
            }
        }
        return $result;
    }
    
    Login or Signup to reply.
  2. Here is a function that will return values with that pattern.

        Route::get('php/', function () {
        function filter_array_by_key($array, $key)
        {
            $result = [];
    
            foreach ($array as $arrayKey => $value) {
                if (strpos($arrayKey, $key . '_') === 0) {
                    $language = substr($arrayKey, strlen($key) + 1);
                    $result[$key][$language] = $value;
                }
            }
    
            return $result;
        }
    
        // Example usage with the correct key:
        $request = [
            'question_ru' => 'question ru',
            'answer_ru' => 'answer ru',
            'question_uz' => 'question uz',
            'answer_uz' => 'answer uz',
            'question_en' => 'question en',
            'answer_en' => 'answer en',
            'question_tz' => 'question tz',
            'answer_tz' => 'answer tz',
        ];
    
        dd(filter_array_by_key($request, 'question'));
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search