Hello how can i convert string to array but it should be in nested format. like i show in the example.
first i tried to explode "/" then i try static variable in foreach loop.. but no luck.
i'm beginner & still confused how to do this..
FROM
$str = 'first/second/third';
To
array(
'first' => array(
'second' => array(
'third' => array(
)
)
)
);
Apply cleverness :p
$keys = explode("/",$str);
$result = array();
$ref = &$result;
foreach($keys as $key) {
$ref[$key] = array();
$ref = &$ref[$key];
}
unset($ref); // delete the reference
Related
I have an array in PHP:-
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"]
Here I want to group together elements based on same ending integer together in json like
$post_data = array(
'0' => array(
'BX_NAME0' => $item_type,
'BX_categoryName0' => $string_key,
'BHA_categories0' => $string_value
),
'1' => array(
'BX_NAME1' => $item_type,
'BX_categoryName1' => $string_key,
'BHA_categories1' => $string_value
),
);
I have Used:- filter_var($key , FILTER_SANITIZE_NUMBER_INT);
to get the integer part of the array elements but don't known how to group them further.
You can do it like below using preg_match():-
$new_array = array();
foreach ($arr as $ar){
preg_match_all('!\d+!', $ar, $matches); //get the number from string
$new_array[$matches[0][0]][$ar] = '';
}
echo "<pre/>";print_r($new_array);
Output:- https://eval.in/715548
It should be something like this:-
$arr = array("BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2");
$post_data = array();
foreach($arr as $value) {
$key = filter_var($value , FILTER_SANITIZE_NUMBER_INT);
if(isset($post_data[$key]) && !is_array($post_data[$key])) {
$post_data[$key] = array();
}
$post_data[$key][] = $value;
}
print_r($post_data);
Tested and works
However, I suggest you use substr() to get the last character of the array item, for performance and stuff..
By using filter_var() method
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"];
foreach($arr as $a){
$int = filter_var($a, FILTER_SANITIZE_NUMBER_INT);
$newarr[$int][$a] = '';
}
print_r($newarr);
Output:-https://eval.in/715581
I have this array in PHP
$fields = array(
0 => array(
'field1' => 'something1',
'field2' => 'something2'
)
)
And I need it to look like this
$fields = array(
'fields1' => 'something1',
'fields2' => 'something2'
)
What function code can I use to get rid of the 0 index in the example?
You can loop through like this...
Create new array
$newArray = [];
Then loop through
foreach($fields as $field){
if(is_array($field)){
foreach($field as $key => $value){
$newArray[$key] = $value;
}
}
}
just take the '0' element from fields:
$fields=$fields[0];
Simple
$fields = reset($fields);
Or
$fields = array_shift($fields);
Create an array, loop through $fields, and merge whatever items are there with the created array.
$final_array = array();
foreach ($fields as $field)
{
$final_array = array_merge($final_array, $field);
}
$fields = $final_array;
This will be able to handle any number of items in either level of the array and compact them into a one-level array.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data)); $list = iterator_to_array($it,false);
Use this to get ride of any extra levels.
Will gives you what you want
I have this php associative array.
array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
)
I would like to convert it into a json output using json_encode() that looks like this;
[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]
How can this be done? The challenging part to me seems like how to add the Location_name and Link_name in front. Thank you very much.
<?php
// original array
$a = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
// transform
$b = array();
foreach($a as $key=>$value) {
$b[] = array('Location_name'=>$key, 'Link_name'=>$value);
}
// output
echo json_encode($b);
?>
Result:
[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]
You Can use StdClass anonymous Objects.
<?php
$newArray = array();
$array = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
foreach ($array as $key => $value) {
$object = new StdClass();
$object->Location_name = $key;
$object->Link_name = $value;
$newArray[] = $object;
}
var_dump(json_encode($newArray));
So first things first:
convert it into a json output using json_encode() that looks like this
This is not possible. json_encode just encodes arrays to JSON, you need to do the formatting work yourself.
And on that note
array_map should do the trick.
Try this:
$arr = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
$output = array_map(
function( $key, $val ){
return array(
"Location_name" => $key,
"Link_name" => $val
);
}, array_keys( $arr ), $arr );
echo json_encode( $output );
In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.
some "simple" problem:
I've this array;
$myArray = array(
'FOO',
'BAR,
);
i want :
$mayArray = array(
'FOO' => array(),
'BAR' => array(),
);
in the moment iam doing it with an foreach:
foreach ($myArray as $key => $val) {
$newArray[$val] = array();
}
$myArray = $newArray;
is there an easyer way ? ;-)
The way you have is pretty easy to understand. But you can also do this:
$myArray = array_fill_keys($myArray, array());
Docs here: http://us2.php.net/manual/en/function.array-fill-keys.php
You can use array_fill_keys, here is example:
$myArray = array_fill_keys($myArray, array());