PHP Dynamic Nested Associative Array - php

I have an associative array which is generated dynamically with the values from database. When I print the whole array, it gives something like this when we put print_r($array).
Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )
When I echo like this,
echo $array['95a5c80811239526fb75cbf31740cc35']['product_id'];
it gives me product id.
But the problem is, the code '95a5c80811239526fb75cbf31740cc35' changes dynamically everytime. I want to echo the product id irrespective of this code.
I tried
$array[]['product_id'];
$array['']['product_id'];
But not working. Can anyone help me? Please ask me if you have any doubts.

You can use reset() in this case:
$array = array(
'95a5c80811239526fb75cbf31740cc35' => array( // dynamic
'product_id' => 2324
),
);
$value = reset($array); // set pointer to first element
echo $value['product_id']; // 2324

Assuming that the code is always the first element in the array:
$array[0]['product_id'];
If you collectively want all of the product ID's:
foreach($array as $product){
$productIds[] = $product['product_id'];
}
// $productIds is now what $array was, but without the codes, so the product_id's are the first elements.

You can use for each for this so that you can get the value of product Id
$array = Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )
foreach($array as $product){
echo $product['product_id'];
}
This would get your desired o/p

IF you are getting problem using Associative array then you can first convert it into numeric as follows
$arr=array( 'first' => array( 'product_id' => 2324) );
$arrr=array_values($arr);
echo $arrr[0]['product_id'];
Output:
2324
Hope this helps and to know about array_values go here

Depending on your situation, there are few possible solutions:
$array = array_shift(array_values(
Array(
'95a5c80811239526fb75cbf31740cc35' =>
Array(
'product_id' => 2324
)
)));
echo $array['product_id']; // 2324
Another solution, probably more efficient:
echo array_shift(array_slice($array, 0, 1)); // 2324
For PHP 5.4+ you could go with:
echo array_values($array)[0]; // 2324

$array[0]['product_id'];
Should do the trick.

Related

PHP rename key in Associative array

I've been searching through the articles on SO for this question and tried many of the solutions in my own code but it's not seeming to work.
I have the following array
$array[] = array("Order_no"=>$order_id,
"Customer"=>$customer_id,
"Product"=>$code_po,
"Product_description"=>$code_description,
"Position"=>$pos,
"Qty"=>$item_qty
);
I am looking to replace the "Order_no" key with a variable from a database query, lets assume in this case the variable is "new_name"
$new = "new_name";
$array[$new]=$array["Order_no"];
unset($array["Order_no"]);
print_r($array);
in the print_r statement I am getting the new_name coming through as the correct order number, but I am still seeing "Order_no" there also, which I shouldn't be seeing anymore.
Thanks.
This is your array:
Array
(
[0] => Array
(
[Customer] => 2
[Product] => 99
[Order_no] => 12345
)
)
One way to do it:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$i_arr = $arr[0];
$i_arr["new_name"] = $i_arr["Order_no"];
unset($i_arr["Order_no"]);
$arr[0] = $i_arr;
print_r($arr);
Another way:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$arr[0]["new_name"] = $arr[0]["Order_no"];
unset($arr[0]["Order_no"]);
print_r($arr);
To flatten your array out at any time:
<?php
$arr = $arr[0];
print_r($arr);
You are using extra level of array (by doing $array[] = ...).
You should do it with [0] as first index as:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
Live example: 3v4l
Another option is get ride of this extra level and init the array as:
$array = array("Order_no"=>$order_id, ...
As $array is also an array, you have to use index:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
The other answers will work for the first time you add to the array, but they will always work on the first item in the array. Once you add another it will not work, so get the current key:
$array[key($array)][$new] = $array[key($array)]["Order_no"];
unset($array[key($array)]["Order_no"]);
If you want the first one, then call reset($array); first.
Change your variable to
$array=array("Order_no"=>$order_id,"Customer"=>$customer_id,"Product"=>$code_po,"Product_description"=>$code_description,"Position"=>$pos,"Qty"=>$item_qty);
or change your code to
$new = "new_name";
$array[0][$new]=$array[0]["Order_no"];
unset($array["Order_no"]);
print_r($array);
Just be careful this would change the order of the array

Get value of an array without using the key name

I am having the following array:
$products = array(
'B004X6ABTM' => array(
'price' => '44.96',
'priceOld' => '59.22',
'percentageSaved' => 24,
'currency' => '$',
'currencyCode' => 'USD'
)
);
The key B004X6ABTM is different from product to product. However, I would like to have a general solution to get the price and currency for every product.
How can I reference the first value of an array, without using the name of the key.
I tried the following, which does not give me any output:
echo $products[0];
Thank you in advance for your replies!
Another option is to use reset.
From the documentation: That will set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.
$value = reset($products);
echo $value["currency"];
echo $value["price"];
That would give you:
$44.96
Demo
You can use as below:
$keys = array_keys( $products);
print_r($products[ $keys[0] ]);
You can use array_values. It will remove keys from array.
$products = array_values($products);
You can get price and currency of all product wise,
foreach ($products as $prod_code => $row) {
echo "Price= ".$row['price']." & Currency=".$row['currency']."<br>";
}

Restructuring Multi Dimensional Array Format

I am struggling with what would appear to be a pretty straight forward task. I have looked at and tried all kinds of functions and suggestion on SO hoping that maybe there is something simple and functional out there. Nothing I tried gives me the logic to do the restructuring.
I have a long complex array. However very much simplified the logic problem I am trying to solve generically is as follows:
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name = Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
and I need to convert it to the following set of arrays (noting the concatenation of the two arrays with a common property id.....
$property1
(
array['charges']
[0] =>IPS2
array ['names']
[0] =>NAME-A
)
$property2
(
array['charges']
[0] ->IPS3
[1] =>IPS4
array['names']
[0] =>NAME-B
[1] =>NAME-c
)
I have tried everything over the course of the last few hours and a simple solution totally evades me.
If you can join the three arrays as you say in comments above this code will generate the look you want.
I loop through the array with property and keep key as the key to find names and charges in the other subarrays.
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name =Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
$arr[] = $cost_type;
$arr[] = $supplier_name;
$arr[] = $propertyid;
$result = array();
Foreach($arr[2] as $key => $prop){
$result[$prop]["charges"][] =$arr[0][$key];
$result[$prop]["names"][] = $arr[1][$key];
}
Var_dump($result);
https://3v4l.org/EilvE
The following code converts the original array in the expected result:
$res = array();
foreach($arr[2] as $k => $foo){ // foreach property
if(!isset($res[$foo])){ // add property if not yet in list
$res[$foo] = array(
'charges' => array($arr[0][$k]),
'names' => array($arr[1][$k])
);
}else{ // add new value to already existing property
$res[$foo]['charges'][] = $arr[0][$k];
$res[$foo]['names'][] = $arr[1][$k];
}
}
Check it out here: https://eval.in/904473
Of course, it assumes a bunch on things about the data, but it should work for any number of items.
And if you need the property in another variable, just access it with $res['name of it].
Run this code you will get smiler result as you want :
$twodimantion=array();
$properties=array('property1','property2','property3');
$charges=array('ISP2','ISP3','ISP4');
$names=array('NAME-A','NAME-B','NAME-C');
foreach ($properties as $key => $property) {
$twodimantion['charge'][$key]=$charges[$key];
$twodimantion['names'][$key]=$names[$key];
$twoarray[$property]=$twodimantion;
}
echo '<pre>';
print_r($twoarray);
echo '</pre>';
I can't say I completely follow what you are trying to do, but I think this may be part of the way there for you.
When trying to restructure data in PHP, it's often helpful to create a empty array (or other data structure) to store the new data in first. Then you find a way to loop over your initial data structure that allows you to insert items into your reformatted structure in the right sequence.
<?php
$properties = []; // Array to hold final result
// Loop over your initial inputs
foreach ($groupsOfValues as $groupName => $groupValues) {
$temp = []; // Array to hold each groupings reformatted data
// Loop over the items in one of the inputs
for ($i=0; $i<count($group) && $i<count($properties)+1; $i++) {
if (!is_array($temp[$groupName])) {
$temp[$groupName] = [];
}
$temp[$groupName][] = $group[$i];
}
$properties[] = $temp;
}

PHP pass by reference issue - can't change type?

I have a weird phenomenon. I hope someone can explain to me what is happening there:
I want to create a filter. The origin is something like '-10' or '10-20' or '20+' (type string) and the result should be 'Under $10', ... as well as 'product_price < 10', ... for a sql command.
But storing the array back on the original string doesn't work. It just delivers '$Array' as result. Is it not possible to pass by reference and change the type?
Thanks for your knowledge!
foreach($filters as &$filter){
preg_match ('#^\-(\d+)$#ism', $filter, $match);
if ($match[1]){
$filter = array(
'Under $'.intval($match[1]),
'product_price < '.intval($match[1])
);
}
...
}
return $filtering;
}
P.S.: I am not looking for a solution, because I could change the origin string into array, or I could change the foreach in to a pass by value and create a new array with the arrays like $newFilter[] = ... I am only curious
You can change it's type. Proof by construction:
<?php
header('Content-type:text/plain');
$arr = array(
'1',
'2',
);
foreach ($arr as &$filter) {
$filter = array($filter);
}
print_r($arr);
?>
Prints:
Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[0] => 2
)
)
You should change your foreach into
foreach($filters as $index => $filter)
and update your filter by doing
$filters[$index] = array(...);
I believe the $filter variable created by the foreach() statement is a copy of the data in the array and not a reference to it.

array_push() with key value pair

I have an existing array to which I want to add a value.
I'm trying to achieve that using array_push() to no avail.
Below is my code:
$data = array(
"dog" => "cat"
);
array_push($data['cat'], 'wagon');
What I want to achieve is to add cat as a key to the $data array with wagon as value so as to access it as in the snippet below:
echo $data['cat']; // the expected output is: wagon
How can I achieve that?
So what about having:
$data['cat']='wagon';
If you need to add multiple key=>value, then try this.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
$data['cat'] = 'wagon';
That's all you need to add the key and value to the array.
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
For Example:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
For changing key value:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
output:
Array ( [firstKey] => changedValue [secondKey] => secondValue )
For adding new key value pair:
$data['newKey'] = 'newValue';
//this will add new key and value because newKey is not available in array
output:
Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey]
=> newValue )
Array['key'] = value;
$data['cat'] = 'wagon';
This is what you need.
No need to use array_push() function for this.
Some time the problem is very simple and we think in complex way :) .
<?php
$data = ['name' => 'Bilal', 'education' => 'CS'];
$data['business'] = 'IT'; //append new value with key in array
print_r($data);
?>
Result
Array
(
[name] => Bilal
[education] => CS
[business] => IT
)
Just do that:
$data = [
"dog" => "cat"
];
array_push($data, ['cat' => 'wagon']);
*In php 7 and higher, array is creating using [], not ()

Categories