Émilie Robert
Émilie Robert

Reputation: 109

Modify key and value inside multidimensional array PHP

I'm trying to modify a key and value from a multidimensional array with PHP

[0] => Array (
    [price] => 1-0
    [shipping] => 0-1
    [description] => 0-1
    [meta_title] => 0-1
    )
[1] => Array (
    [price] => 1-0
    [shipping] => 0-1
    [meta_title] => 0-1
    )

Let's say I wanna modify description value and key name in 0, I wanna do with index numbers for some reasons, my code so far and where I'm stucked:

$pageID = 0;
$text_id = 2;
$i=0;
foreach($oJson[$pageID] as $t => $f){
   if($i==$text_id){
   }
   $i++;
}

Desired result:

[0] => Array (
        [price] => 1-0
        [shipping] => 0-1
        [modified_description] => 2-3
        [meta_title] => 0-1
        )
    [1] => Array (
        [price] => 1-0
        [shipping] => 0-1
        [meta_title] => 0-1
        )

Thanks a lot for your precious help.

Upvotes: 1

Views: 121

Answers (2)

user5051310
user5051310

Reputation:

Since you want to keep the associative key order, you can use array_keys, array_values, and array_combine.

$pageID = 0;
$text_id = 2;

$newKeys = array_keys($oJson[$pageID]);
$newValues = array_values($oJson[$pageID]);

$newKeys[$text_id] = 'modified_' . $newKeys[$text_id];
$newValues[$text_id] = '2-3';

$oJson[$pageID] = array_combine($newKeys, $newValues);

Upvotes: 1

aslawin
aslawin

Reputation: 1981

Try this:

$oJson = array('0' => Array (
    'price' => '1-0',
    'shipping' => '0-1',
    'description' =>'0-1',
    'meta_title' => '0-1',
    ),
'1' => Array (
    'price' => '1-0',
    'shipping' => '0-1',
    'meta_title' => '0-1',
    )
);

$pageID = 0;
$text_id = 2;

foreach($oJson as $key => $subArray)
{
    if($key == $pageID)
    {
        $tempArray = array();
        for($i = 0; $i < count($subArray); $i++)
        {
            if($i == $text_id)
            {
                $tempArray = array_slice($subArray, 0, $text_id);
                $tempArray['modified_description'] = '2-3';
                $tempArray = array_merge($tempArray, array_slice($subArray, $text_id + 1));
            }
        }

        if(!empty($tempArray))
            $oJson[$key] = $tempArray;
    }
}


print_r($oJson);

Working example: CLICK!

Upvotes: 1

Related Questions