Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP manipulating multidimensional array values

Tags:

arrays

php

I have a result set as an array from a database that looks like:

array (
    0 => array (
        "a" => "something"
        "b" => "something"
        "c" => "something"
    )
    1 => array (
        "a" => "something"
        "b" => "something"
        "c" => "something"
    )
    2 => array (
        "a" => "something"
        "b" => "something"
        "c" => "something"
    )
)

How would I apply a function to replace the values of an array only on the array key with b? Normally I would just rebuild a new array with a foreach loop and apply the function if the array key is b, but I'm not sure if it's the best way. I've tried taking a look at many array functions and it seemed like array_walk_recursive is something I might use, but I didn't have luck in getting it to do what I want. If I'm not describing it well enough, basically I want to be able to do as the code below does:

$arr = array();
foreach ($result as $key => $value)
{
    foreach ($value as $key2 => $value2)
    {
        $arr[$key][$key2] = ($key2 == 'b' ? $this->_my_method($value2) : $value2);
    }    
}

Should I stick with that, or is there a better way?

like image 691
Joker Avatar asked Jan 02 '11 06:01

Joker


People also ask

How do you loop through a multidimensional array in PHP?

Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.

How can create multidimensional array in array in PHP?

It can be created using nested array. These type of arrays can be used to store any type of elements, but the index is always a number. By default, the index starts with zero. print_r( $myarray );

What is multidimensional array in PHP explain it with simple PHP?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

What is nested array in PHP?

What is nested array in PHP? In the above example Create a variable $arr with value an nested array. Here at the place of array's first element there is also an array with three value like $arr[0][0]=10, $arr[0][1]=10, and $arr[0][2]=10.


1 Answers

Using array_walk_recursive:

If you have PHP >= 5.3.0 (for anonymous functions):

array_walk_recursive($result, function (&$item, $key) {
    if ($key == 'b') {
        $item = 'the key is b!';
    }
});

Otherwise something like:

function _my_method(&$item, $key) {
    if ($key == 'b') {
        $item = 'the key is b!';
    }
}
array_walk_recursive($result, '_my_method');
like image 101
thirtydot Avatar answered Sep 24 '22 02:09

thirtydot