0

I am trying to get a value from an array of arrays:

$headers = {array} [10]
 0 = {array} [2]
 1 = {array} [2]
 2 = {array} [2]
 3 = {array} [2]
 4 = {array} [2]
 5 = {array} [2]
 6 = {array} [2]
 7 = {array} [2]
 8 = {array} [2]
  name = "X"
  value = "something"
 9 = {array} [2]

So I want to find the value where the name is X?

I tried array_search(), maybe I need to flatten the array?

Cheers,

Mick

Mick
  • 1,401
  • 4
  • 23
  • 40

4 Answers4

1

you can convert array to laravel collection and apply where() function

below is this solution

$headers  = [
    [
        "name" => "n",
        "value" => "somthing",
    ],
    [
        "name" => "x",
        "value" => "somthing",
    ],
    [
        "name" => "n",
        "value" => "somthing",
    ],
    [
        "name" => "n",
        "value" => "somthing",
    ],
    [
        "name" => "n",
        "value" => "somthing",
    ],
];

$collcetion = collect($headers);
$result = $collcetion->where("name", "x")->first();
dd($result);

ref link

https://laravel.com/docs/8.x/collections#method-collect https://laravel.com/docs/8.x/collections#method-where

Kamlesh Paul
  • 11,778
  • 2
  • 20
  • 33
1

If you have unique values for your names, then you can use array_column, to build map between keys, and then pluck out your desired item.

Note that if you had multiple names of the same value the latter would overwrite the any previous assignments.

<?php
$items =
[
    [
        'name'     => 'Johnny',
        'vocation' => 'Ratter'
    ],
    [
        'name'     => 'Donald',
        'vocation' => 'Draper'
    ],
    [
        'name'     => 'Eddie',
        'vocation' => 'Trucker'
    ]
];

echo array_column($items, 'vocation', 'name')['Eddie'] ?? null;

Output:

Trucker
Progrock
  • 7,373
  • 1
  • 19
  • 25
0

You have two ways

  1. Using native PHP
foreach ($headers as $header) {
   if ($header['name'] == 'x') {
       // TODO ...
       break;
   }
}
  1. Using Laravel Collection
$result = collect($headers)->filter(function ($header) {
   if ($header['name'] == 'x') {
       return $header;
   }
})->values();
mmabdelgawad
  • 2,385
  • 2
  • 7
  • 15
0

Here is a code to search by key, if you want by both key and value, check dupplicate answer How to search by key=>value in a multidimensional array in PHP

function search($array, $key)
{
    $results = array();
    search_r($array, $key, $results);
    return $results;
}

function search_r($array, $key, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key])) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        search_r($subarray, $key, $results);
    }
}
N69S
  • 16,110
  • 3
  • 22
  • 36