In PHP, I am using multidimensional array with key and value but when ever their is more than one value old value replaced with new value. I want to store more than one value in with same array with same key.
//all table data store in array
Array
(
[TB1] => Array
(
[index] => 1
[user1_id] => 9
[is_searched] => false
[relation] => father
)
[TB2] => Array
(
[index] => 1
[user1_id] => 10
[is_searched] => false
[relation] => mother
)
[TB3] => Array
(
[index] => 1
[user1_id] => 1
[is_searched] => false
[relation] => son
)
[TB4] => Array
(
[index] => 1
[user1_id] => 4
[is_searched] => false
[relation] => daughter
)
)
i have search on google some of them are said to used numeric index instead of key but i need to use key for my work, in google i didnt get solution as i need. i need solution which can hold multiple values in single array using same key not numeric index, below i have put output array as i want in php. further from this array i have to also retrive data
Array
(
[TB1] => Array
(
[index] => 1
[user1_id] => 9
[is_searched] => false
[relation] => father
[index] => 2
[user1_id] => 14
[is_searched] => false
[relation] => father
[index] => 3
[user1_id] => 2
[is_searched] => false
[relation] => father
[index] => 4
[user1_id] => 8
[is_searched] => false
[relation] => father
[index] => 5
[user1_id] => 11
[is_searched] => false
[relation] => father
)
[TB2] => Array
(
[index] => 1
[user1_id] => 10
[is_searched] => false
[relation] => mother
)
[TB3] => Array
(
[index] => 1
[user1_id] => 1
[is_searched] => false
[relation] => son
[index] => 2
[user1_id] => 7
[is_searched] => false
[relation] => son
[index] => 3
[user1_id] => 17
[is_searched] => false
[relation] => son
)
[TB4] => Array
(
[index] => 1
[user1_id] => 4
[is_searched] => false
[relation] => daughter
)
)
i have also try to use key name with loop variables so that when loop starts second time the key name is changed like below example i dont want that bcoz its complicated in further task to retrive data
the solution should be easy not complicated, in other languages we can use objects so we can store more than one values in array but in php it is not possible maybe it is possible in core php but i don’t core php
Array
(
[TB1] => Array
(
[index0] => 1
[user1_id0] => 9
[is_searched0] => false
[relation0] => father
[index1] => 2
[user1_id1] => 14
[is_searched1] => false
[relation1] => father
[index2] => 3
[user1_id2] => 2
[is_searched2] => false
[relation2] => father
)
)
2
Answers
how can i make this type of structure in php bcoz in this array i am storing data from database like this
This is not possible. Associative arrays require unique keys. So, You can’t do this:
The typical data structure you’d see for this use case is an indexed array of associative arrays:
That array structure can then itself be a value in an associative array, so you can do this:
You’d consume this via: