PHP array's, how to access keys and values - php

Trying to learn multidimensional arrays but seem to constantly struggle with accessing them. I still have not got grasps of how you access them using index, keys, values.
How do I get to the actual word "Title" and it's value?
Here I have one I was playing with.
$shop = array( array( "Title" => "rose",
"Price" => 1.25,
"Number" => 15
),
array( "Title" => "daisy",
"Price" => 0.75,
"Number" => 25,
),
array( "Title" => "orchid",
"Price" => 1.15,
"Number" => 7
)
);
Which prints a structure such as this:
Array
(
[0] => Array
(
[Title] => rose
[Price] => 1.25
[Number] => 15
)
[1] => Array
(
[Title] => daisy
[Price] => 0.75
[Number] => 25
)
[2] => Array
(
[Title] => orchid
[Price] => 1.15
[Number] => 7
)
)
echo $shop[0][0][0]; //I Expect "rose" but I get "Undefined offset: 0"
echo $shop['Price']; //I expect 1.25 but I get "Undefined index: Price"
foreach($shop as $key=>$value)
{
echo $key; //I expect the key values "Title/Price/Number" instead I get Index numbers 0 1 2
echo $value; //I expect all values of keys e.g. "rose",1.25,15/"daisy",0.75,25/"orchid",1.15,7 Instead I get Array to string conversion error
}
What I am trying to do, is take all the title and value from the shop array, and put it into a new array called $x = array(); and then take a car key/value from a different array and combine them together.
so the new array ends up looking like this:
Array
(
[0] => Array
(
[Title] => rose //from $shop array
[Car] => Mercedez //from $car array
)
[1] => Array
(
[Title] => daisy //from $shop array
[Car] => Ford //from $car array
)
[2] => Array
(
[Title] => orchid //from $shop array
[Car] => Bentley //from $car array
)
)
Also is there a way to access the actual name of the key "title" and not a index number?

You have an array of arrays, therefore you'll need two loops.
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $key;
echo $value;
}
}

Try this -
$newarray = array();
foreach($shop as $key=>$value) {
$newarray[$key]['Title'] = $value['Title'];
$newarray[$key]['Number'] = $value['Number'];
}
echo "<pre>";print_r($newarray);
Here, $newarray will give you output like this.
Array
(
[0] => Array
(
[Title] => rose
[Number] => 15
)
[1] => Array
(
[Title] => daisy
[Number] => 25
)
[2] => Array
(
[Title] => orchid
[Number] => 7
)
)

You could access by $shop[0]['Title']
0 means the first item in array and this item is also an array, which contains string keys so 'title' as second level.
To iterate it use:
//Syntax array as key => value (value is in this case also an array)
foreach($shop as $iterator_level1 => $shop_set){
//so you can access the 2. level by string key.
echo $shop_set['title'];
}
Hope this is helpful.

Related

Create an array from an associative array using one of its value in a key value pair

I've a following associative array named $data. Here is some same key value pairs
Array
(
[0] => Array
(
[id] => 1
[config_id] => 31
[language] => "English"
)
[1] => Array
(
[id] => 2
[config_id] => 33
[language] => "English"
)
[2] => Array
(
id] => 3
[config_id] => 32
[language] => "French"
)
)
And i wanted to convert this array as
Array
(
["English"] => Array(
[0]=> Array
(
[id] => 1
[config_id] => 31
)
[1] => Array
(
[id] => 2
[config_id] => 33
)
)
["French"] =>
Array(
[0]=> Array
(
[id] => 3
[config_id] => 32
)
)
)
)
I need the language as key in the output array,Can anyone help me out to resolve this issue? Thanks in advance.
I tried the following code, but printed the last array value only
$arry = array();
foreach ($data as $val) {
$arry[$val->language]["id"] = $val->id;
$arry[$val->language]["config_id"] = $val->config_id;
}
You are nearly there, just need to make the new array all in one go and just use the $arry[$val->language][] to create a new sub array under that new or existing language key.
Also $data is an array or arrays not an array of objects so the addressing of the items was wrong.
$arry = array();
foreach ($data as $val) {
$arry[$val->language][] = ['id' => $val['id'], 'config_id' => $val['config_id']];
}

split one array have two key split into two array in php

Question :
I have one array have two key or more split into two or more create array based on array in php.
my Array :
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I want output like this :
output:
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
)
)
array(
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I am not sure how you want to store those arrays, but let me help you.
I assume you have a datastructure like this, so one array with multiple values.
array (
key1 => ...values...,
key2 => ...values...,
...
key_n => ...values...
)
And you want something like this, si multiple arrays with single keys well you need to store that array somehow.
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
If you do not know the exact number of arrays, you can't $array1, $array2, ... $array_n and it also not efficent, so you shoudl have an array of arrays. So something like this:
array(
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
)
So you should iterate trough the keys of the input array and then
So the code
<?php
//example input array
$arr = array (
"key1" => "val1",
"key2" => "val2"
);
$keys = array_keys($arr); //get the keys of the input array, see phpdoc
$output = [];
foreach($keys as $key) {
$output[] = array ($arr[$key]);
}
?>
This will output an array of arrays, with single key of the inner array.
If this is not you answer, reply.
Research:
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/control-structures.foreach.php
php.net - arrays manual Example #6 Accessing array elements
Maybe this document will help you
This may also help you
<?php
$stdArray = array(
"foo" => "bar",
42 => 24,
"dimensional" => array(
"fname" => "jon",
"lname" => "doe",
),
"multi" => array(
"RAJAHMUNDRY" => array(
"unspcp_code" => 46182005,
"head_quarter" => "RAJAHMUNDRY",
0 => 2
),
"HYDERABAD" => array(
"unspcp_code" => 46182005,
"head_quarter" => "HYDERABAD",
0 => 2
),
)
);
print_r($stdArray);
print_r($stdArray["multi"]);
print_r($stdArray["multi"]["RAJAHMUNDRY"]);

Change index of multidimensional array PHP

I've tried some solutions from:
In PHP, how do you change the key of an array element?
php array from multidimensional array keys values
But its is not exacly what i need, i tried to mix some solutions but notting helped.
I have an array from my database:
Array (
[0] => Array (
[ID] => 1
[USER_ID] => 1
[DATA] => UNIQUE
[VALUE] => buuu )
[1] => Array (
[ID] => 2
[USER_ID] => 1
[DATA] => NICKNAME
[VALUE] => NoAd ) )
And i want to transform that database to:
Array (
[UNIQUE] => buuu
[NICKNAME] => NoAd
[any new [2]...[3]... from previous array
after that code:
foreach($playerdata as $segment){
foreach($segment as $key => $value ){
$newArray[$value] = $value;
}
}
my array looks like:
Array ( [UNIQUE] => UNIQUE
[buuu] => buuu
[NICKNAME] => NICKNAME
[NoAd] => NoAd )
i tried use 3x foreach but it ends in error all time i think i need to change some variables in my foreach but no idea how.
Now that I see the other answers it seems it's array_column you are looking for.
It returns an array column and the third parameter is what the key name should be.
$player_data = array(array(
"ID" => 1,
"USER_ID" => 1,
"DATA" => "UNIQUE",
"VALUE" => "buuu"
),
array(
"ID" => 1,
"USER_ID" => 1,
"DATA" => "NICKNAME",
"VALUE" => "NoAd"
));
$new = array_column($player_data, "VALUE", "DATA");
var_dump($new);
Output:
array(2) {
["UNIQUE"]=>
string(4) "buuu"
["NICKNAME"]=>
string(4) "NoAd"
}
https://3v4l.org/ZAkgZ
There is no need for loops to solve this.
lets assume $playerdata has the below values
Array (
[0] => Array (
[ID] => 1
[USER_ID] => 1
[DATA] => UNIQUE
[VALUE] => buuu )
[1] => Array (
[ID] => 2
[USER_ID] => 1
[DATA] => NICKNAME
[VALUE] => NoAd ) )
[2]----
[3]----
$newArray = [];
foreach($playerdata as $record) {
$newArray[$record['DATA']] = $record['DATA'];
$newArray[$record['VALUE']] = $record['VALUE'];
}
print_r($newArray);
You could try something like the following:
$newArray = array();
foreach($playerdata as $segment){
$newArray[$segment['DATA']] = $segment['VALUE'];
}
This code gets the DATA as key and VALUE as value from each part of the array and stores it in $newArray.

How do you change a Multidimensional Array Key to a Childs Key Value?

I'm trying to rename the parent keys in a Multidimensional Array to the value of a child key.
For example in the code below I would like to change the key [0] to [111] and the key [1] to [222] so it is easy for me to identify keys later for an array merge.
Array (
[0] => Array ( [product_id] => 111 [product_name] => Foo [quantity] => 4 )
[1] => Array ( [product_id] => 222 [product_name] => Bar [quantity] => 2 )
)
I've tried various ways of doing this but after entering a loop, I can't work out how to affect the parent key and assume it's impossible after passing it to a variable. Is there an easy solution to change the key I am missing or is it a case of entering the loop and rebuilding a new array with the desired key?
One-line solution using array_combine and array_column functions:
$result = array_combine(array_column($arr, 'product_id'), $arr);
print_r($result);
The output:
Array
(
[111] => Array
(
[product_id] => 111
[product_name] => Foo
[quantity] => 4
)
[222] => Array
(
[product_id] => 222
[product_name] => Bar
[quantity] => 2
)
)
You need to create a new array, such as:
$original = array(
[0] => Array ( [product_id] => 111 [product_name] => Foo [quantity] => 4 )
[1] => Array ( [product_id] => 222 [product_name] => Bar [quantity] => 2 )
)
$new = array();
foreach ($original as $val) {
$new[$val->product_id] = $val;
}
create new array use foreach to loop through your old array and assign the value of new one
<?php
$oldArray[0] = Array ("product_id"=> 111 , "product_name" => "Foo" , "quantity" => 4 );
$oldArray[1] = Array ("product_id"=> 222 , "product_name" => "Bar" , "quantity" => 2 );
$newArray=array();
foreach($oldArray as $childarray){
$newArray[$childarray['product_id']]=array('product_id'=>$childarray["product_id"],'product_name'=>$childarray["product_name"],'quantity'=>$childarray["quantity"]);
}
echo "<pre>";
print_r($newArray);
echo "</pre>";
?>

How to get index number of associative array that has a value in php

I have this associative array in php,
Array ( [items] => Array ( [0] => Array ( [Desc] => Tech Pen [Qty] => 15 ) [1] => Array ( [Desc] => Ballpen [Qty] => 4 ) ) )
How to get the index number that has a Description value of Tech Pen?
The answer should be, [0].
A possible solution to get your index number is to loop the $array using a foreach:
$array = array(
"items" => array(
array(
"Desc" => "Tech Pen",
"Qty" => 15
),
array(
"Desc" => "Ballpen",
"Qty" => 4
),
)
);
foreach ($array['items'] as $key => $item) {
if($item['Desc'] === 'Tech Pen') {
echo "The value 'Tech Pen' has index number: $key";
}
}
array_search() — Searches the array for a given value and returns the corresponding key if successful. Read More
Try:
$key=array_search('Tech Pen', $array);

Categories